Question

I'm trying to use a C# DLL that I have access to the code of, but I can't actually change the code and build a custom version of it. The calling code is a C# WinForms project and the C# DLL also uses WinForms to handle Windows system events. The problem is that the DLL uses Application.Run() inside of it using a background thread, and there's built-in way to kill or stop that thread. Here is a snippet of the code:

public class DllClass
{
    private Thread uithread = null;
    private bool uithreadstarted = false;

    public DllClass()
    {
        uithread = new Thread(new ThreadStart(RunDll));
        uithread.IsBackground = true;
        uithread.SetApartmentState(ApartmentState.STA);
        uithread.Start();
        do
        {
            Thread.Sleep(100);
        } while (uithreadstarted == false);
    }

    private void RunDll()
    {
        //other init stuff here
        uithreadstarted = true;
        Application.Run();
    }
}

Apparently the way I'm expected to kill it is by using Application.Exit(), but that also exits my own WinForms project, which is not what I want to happen. If I just close my application without calling Application.Exit(), the DLL continues running in the background. I want to be able to instantiate the DllClass object, use it, and then shut it down when I'm done. I came up with a method to get the Thread object of the thread that it's running in, but calling Thread.Abort() on it does not actually kill the thread. Is there any way to forcibly abort the Application.Run() call from outside of the DLL?

Was it helpful?

Solution 2

you will need to get an instance of the form that is running in the other thread then call form.BeginInvoke and from there call Application.Exit

OTHER TIPS

If you can find a window handle that was created by the DLL background thread (such as a form or hidden application window), you can post a WM_QUIT message to that handle and that should cause the DLL to exit the message loop cleanly.

How about Application.ExitThread

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top