Stopping work from one thread using another thread

后端 未结 2 666
南笙
南笙 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();
    }
    

提交回复
热议问题