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
}
}