0

This problem is similar to another stack overflow question asked here: How to kill a thread instantly in C#? This question does a good job of explaining the problem, and providing a solution for a similar problem. My problem is that the code is event driven, and does not run in a loop.

I am trying to fix an error upon closing my application. The app has a class instantiated in a thread that listens for events, does some work once getting the event, and continues listening. These events could happen once per session or 10's of thousands of times. All of this is working well.

This thread is started in the constructor of the main application, and should only end when the application is closed, but half the time the thread hangs, and has to be closed through task manager, the other half of the time the app crashes.

What is the correct way to end this thread?

Here is some simplified code:

Public Main_App_Constructor()
{
    ...
    usrIface = new UserInterface();
    usrIface.Start();
    ...
}

private void Application_Exit(object sender, ExitEventArgs e)
{
    ...
    usrIface.Stop();
    ...
}

Public class UserInterface
{
    CommandListener listener;
    Thread listnerThread;   

    Public UserInterface()
    {
        listener = new CommandListener();
        listnerThread = new Thread(new 
        ThreadStart(listner.BeginListneingForEvents));
        listnerThread.SetApartmentState(ApartmentState.STA);
        listnerThread.Name = "Listner";
    }

    Public void Start()
    {
        listnerThread.Start();
    }

    Public void Stop()
    {
        listnerThread.Abort();
    }
}

Public class CommandListener
{
    EventLauncher eventer;

        Public CommandListener()
    {
        eventer = new EventLauncher();

        eventer.event1 += eventer_event1;
        eventer.event2 += eventer_event2;
        eventer.event3 += eventer_event3;
        ...
    }

    private void eventer_event1(object sender, eventArgs e)
    {
        //Does stuff
    }

    private void eventer_event2(object sender, eventArgs e)
    {
        //Does stuff
    }

    private void eventer_event3(object sender, eventArgs e)
    {
        //Does stuff
    }
}
  • I believe I have clarified how my question is different than the one referenced. If they are the same please clarify how the solution in the other thread should be implemented. –  Oct 03 '17 at 19:21

1 Answers1

-1

According to Microsoft's documentation,

The thread is not guaranteed to abort immediately, or at all.

Possible solutions were discussed in this Stack Overflow question here. Some suggest used a shared variable or setting a state variable in the thread itself to ask for it to stop its operations. Another suggestion was to add the SecurityPermissionAttribute attribute and set ControlThread equal to true. I haven't played with it myself, but I would start at these places before moving forward.

arjabbar
  • 6,044
  • 4
  • 30
  • 46