如何停止一个线程,当我的WinForm应用程序关闭我的、线程、应用程序、WinForm

2023-09-02 01:58:55 作者:☆无心☆

我有一个单身,有一个正在运行的线程用于从服务器获取记录。 但是,当我停止我的WinForm应用程序的线程保持运行。我试图创建我的单身中止,如果它运行的线程析构函数,但它不具备线程上的任何影响 - 我知道,析构函数被诱发。

I have a singleton that has a running thread for obtaining records from a server. But when I stop my winform application the thread keeps running. I have tried to create a destructor in my singleton to abort the thread if it running, but it does not have any effect on the thread - I know that the destructor is being evoked.

我要寻找的建议对我应该怎么关闭线程时,我的应用程序关闭。 谢谢

I am looking for suggestions on how I should shut down a thread when my application closes. thanks

C#,.NET2

推荐答案

最好的选择,如果可能的话在你的应用程序,是合作取消。

The best option, if possible in your application, is cooperative cancellation.

当没有更多的code来执行的线程将自动停止。因此,当用户关闭应用程序时,设置一个标志,指示你的线程应该停止。该线程需要不时检查时间,如果该标志被设置,如果是,停止从服务器和返回获取记录。

A thread automatically stops when it has no more code to execute. So, when the user closes your application, you set a flag indicating that your thread should stop. The thread needs to check from time to time if the flag is set and, if so, stop obtaining records from the server and return.

作为@Hans帕桑特指出,BackgroundWorker内置了支持这一点。 如果可以升级,在.NET Framework 4.0中引入了一整套支持合作消除新类异步操作。 As @Hans Passant noted, BackgroundWorker has built-in support for this. If you can upgrade, the .NET Framework 4.0 introduces a whole set of new classes that support cooperative cancellation of asynchronous operations.

另外,也可以推出自己的解决方案,例如:

Otherwise, you can roll your own solution, for example

static bool isCancellationRequested = false;
static object gate = new object();

// request cancellation
lock (gate)
{
    isCancellationRequested = true;
}

// thread
for (int i = 0; i < 100000; i++)
{
    // simulating work
    Thread.SpinWait(5000000);

    lock (gate)
    {
        if (isCancellationRequested)
        {
            // perform cleanup if necessary
            //...
            // terminate the operation
            break;
        }
    }
}