Stopping work from one thread using another thread

后端 未结 2 616
南笙
南笙 2021-01-21 19:03

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

相关标签:
2条回答
  • 2021-01-21 19:59

    I have a couple of quick comments:

    1. Avoid using Thread.Abort() here's why.
    2. Make your thread a background thread: 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();
    }
    
    0 讨论(0)
  • 2021-01-21 20:06

    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.

    0 讨论(0)
提交回复
热议问题