温馨提示×

C#多线程如何安全退出

c#
小樊
82
2024-06-28 09:30:30
栏目: 编程语言

在C#中,可以通过使用标志位来安全退出多线程。以下是一个示例代码:

using System;
using System.Threading;

class Program
{
    private static bool isRunning = true;

    static void Main()
    {
        Thread thread = new Thread(Worker);
        thread.Start();

        Console.WriteLine("Press any key to stop the thread...");
        Console.ReadKey();

        isRunning = false;
        thread.Join();
        Console.WriteLine("Thread stopped.");
    }

    static void Worker()
    {
        while (isRunning)
        {
            Console.WriteLine("Thread is running...");
            Thread.Sleep(1000);
        }
    }
}

在上面的示例中,定义了一个静态的标志位isRunning来控制线程的运行状态。在主线程中,启动了一个工作线程,并在按下任意键时将isRunning设置为false,然后等待工作线程结束。在工作线程中,通过检查isRunning的值来控制线程是否继续运行。当isRunningfalse时,工作线程会安全退出。

另外,也可以使用CancellationToken来实现线程的安全退出。具体使用方法可以参考C#中的CancellationToken文档。

0