Not sure if my title is worded well, but whatever :)
I have two threads: the main thread with the work that needs to be done, and a worker thread that contains a form wi
I have a couple of quick comments:
Thread.Abort()
here's why.Thread.IsBackground = true
(this will automatically exit the thread when your app exits).Here is a detailed discussion on how to safely stop a thread from running: Is it safe to use a boolean flag to stop a thread from running in C#
To stop the work on the main thread you'd have to do something like this:
boolean volatile isRunning = true;
static void Main(...)
{
// ...
// Working
for (i = 0; i <= 10000; i++)
{
semaphore.WaitOne();
if (!isRunning) break; // exit if not running
if (pBar.Running)
bgworker_ProgressChanged(i);
semaphore.Release();
}
//...
t1.Interrupt();// make the worker thread catch the exception
}
//
void cancelButton_Click(object sender, EventArgs e)
{
isRunning = false; // optimistic stop
semaphore.Release();
}
I recommend using CancellationTokenSource, which can handle this kind of complex scenario. It's part of the Task Parallel Library but does not actually have to be used with Task
objects; it can just as easily be used with old-style Thread
objects.
Of course, if you have the time, I'd recommend defining the main thread's work as a Task
object (running on the main UI thread by using TaskScheduler.FromCurrentSynchronizationContext
).
Note that everything above assumes .NET 4.0. If you're still stuck on the old platform, you'll just have to have a bool cancelled;
field protected by a lock
or some such thing. Tip: don't call Thread.Abort
; it's evil.