代码之家  ›  专栏  ›  技术社区  ›  fishhead

当winform应用程序关闭时,如何停止线程

  •  12
  • fishhead  · 技术社区  · 16 年前

    但是当我停止winform应用程序时,线程会继续运行。我试图在我的单例中创建一个析构函数,如果线程正在运行,就中止它,但是它对线程没有任何影响-我知道析构函数正在被调用。

    我正在寻找建议,我应该如何关闭线程时,我的应用程序关闭。 谢谢

    C#,.net2

    2 回复  |  直到 16 年前
        1
  •  9
  •   dtb    16 年前

    否则,您可以推出自己的解决方案,例如

    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;
            }
        }
    }
    
        2
  •  70
  •   didier    16 年前

    线程可以是:

    • 前台:将保持你的程序,直到它完成。
    • 背景:将在您关闭应用程序时终止。

    创建线程时,默认情况下它是前台线程。

    Thread t = new Thread(myAction);
    t.IsBackground = true;
    t.Start();