First of all, Thread.Abort() is evil - got it! Now let me explain my situation...
Situation:
I have a dashboard that only displays current running status to the user. It executes various select queries against a Sql Server DB and performs some calculations that are eventually displayed to the user on the dashboard. The user can open multiple dashboards at the same time. I have a timer thread that refreshes the dashboard every few seconds. That timer thread spawns another thread (actually queues work on a threadpool) to perform long running calculations/queries.
The Problem:
When the user clicks the X to close the Dashboard window, it needs to shut down right away (say within a second, I think 2 seconds is too long). So I use this code:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_timerThread.Abort();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
// we're on the timer thread now
try
{
RefreshUi();
}
catch (ThreadAbortException)
{
System.Threading.Thread.ResetAbort();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The problem is sometimes the ThreadAbortException is caught, and sometimes it isn't. I find it's mostly uncaught when in the middle of executing queries.
[UPDATE] I've recently discovered I can catch the ThreadAbortException if I check the innerexception.
Questions:
Thanks
Right way to do this will be
ManualResetEvent
handled in background threads and fired from main thread when it's time to close.AutoResetEvent
handlers and gracefully exiting threads