Stopping work from one thread using another thread

Posted by 113483626144458436514 on Stack Overflow See other posts from Stack Overflow or by 113483626144458436514
Published on 2010-06-18T16:11:15Z Indexed on 2010/06/18 16:13 UTC
Read the original article Hit count: 243

Filed under:
|

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 with a progress bar and a cancel button. In normal code, it would be the other way around, but I can't do that in this case.

When the user clicks the cancel button, a prompt is displayed asking if he wants to really cancel the work. The problem is that work continues on the main thread. I can get the main thread to stop work and such, but I would like for it to stop doing work when he clicks "Yes" on 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();
}

I could theoretically include a prompt in the cancelWatch() function, but then I would have to do that everywhere I'm implementing this class.

© Stack Overflow or respective owner

Related posts about c#

Related posts about threads