Stop work from one thread using another thread

Not sure my headline is well worded, but whatever :)

I have two threads: the main thread with the work to be done, and the workflow containing the form with a progress bar and a cancel button. In normal code, this would be the other way around, but I cannot do this in this case.

When the user clicks the cancel button, a prompt is displayed asking if he really wants to cancel the job. The problem is that the work continues in the main thread. I can make the main thread stop working and so on, but I would like it to stop working when it clicks “Yes” at the prompt.

Example:

// Main thread work starts here    
    t1 = new Thread(new ThreadStart(progressForm_Start));
    t1.Start();

    // Working
    for (i = 0; i <= 10000; i++)
    {
        semaphore.WaitOne();
        if (pBar.Running)
            bgworker_ProgressChanged(i);
        semaphore.Release();
        if (pBar.IsCancelled) break; 
    }

    t1.Abort(); 
// Main thread work ends here

// Start progress bar form in another thread
void progressForm_Start()
{
    pBar.Status("Starting");
    pBar.ShowDialog();
}

cancelWatch(), , .

+1
2

:

  • Thread.Abort() , .
  • : Thread.IsBackground = true ( , ).

, : , #

, - :

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();
}
+1

CancellationTokenSource, . , Task; Thread .

, , Task ( TaskScheduler.FromCurrentSynchronizationContext).

, .NET 4.0. , bool cancelled;, lock . : Thread.Abort; .

+1

All Articles