I want to start a thread that listens for events and handles them in the background. This is what I've done so far:
private Thread mThread;
private bool mKeepHandlingIt;
private void Init()
{
mKeepHandlingIt = true;
mThread = new Thread(ProcessEvents);
mThread.SetApartmentState(ApartmentState.STA);
mThread.Start();
}
private void ProcessEvents()
{
StaticClass.CoolEvent += HandleIt;
StaticClass.StartDoingStuff();
while (mKeepHandlingIt)
{
Application.DoEvents();
}
StaticClass.StopDoingStuff();
StaticClass.CoolEvent -= HandleIt;
}
private void HandleIt(object sender, EventArgs e)
{
//Handles it
}
protected override void Dispose()
{
if (mThread != null)
{
mKeepHandlingIt = false;
mThread.Join();
}
}
Is there a better approach to this? Like a thread class that would be better suited for this purpose? BackgroundWorker did not seem like a better choice in this case...
If this is a good approach, though, then I have a problem that I can't quite understand. The above solution works fine for listening to events and handling them, but when Dispose is called and mKeepHandlingIt is set to false, the while loop IS exited (debugger doesn't break if I place a breakpoint in the loop) but no code after the loop is executed and mThread.Join never returns. Basically... what I want to know is: how do I stop the thread and then make sure not to continue before it has cleaned up?