c# - 如何取消线程?

标签 c# multithreading

如果是BackgroundWorkere.Cancel - DoWork - 事件处理程序的属性可以报告取消。

我怎样才能用 Thread 达到同样的目的?对象?

最佳答案

这是一种实现方法的完整示例。

private static bool _runThread;
private static object _runThreadLock = new object();

private static void Main(string[] args)
{
    _runThread = true;
    Thread t = new Thread(() =>
    {
        Console.WriteLine("Starting thread...");
        bool _localRunThread = true;
        while (_localRunThread)
        {
            Console.WriteLine("Working...");
            Thread.Sleep(1000);
            lock (_runThreadLock)
            {
                _localRunThread = _runThread;
            }
        }
        Console.WriteLine("Exiting thread...");
    });
    t.Start();

    // wait for any key press, and then exit the app
    Console.ReadKey();

    // tell the thread to stop
    lock (_runThreadLock)
    {
        _runThread = false;
    }

    // wait for the thread to finish
    t.Join();

    Console.WriteLine("All done.");    
}

简而言之;该线程检查一个 bool 标志,并在该标志为 true 时一直运行。与调用 Thread.Abort 相比,我更喜欢这种方法,因为它看起来更好更简洁。

关于c# - 如何取消线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1865574/

相关文章:

c# - C# 和 C++ 中 try block 的“返回”

c# - 使用绑定(bind)重定向升级两个项目之一

c++ - 两次调用 pthread_join() 时 glibc pthread_join 崩溃

c++ - 从另一个线程调用 CFRunLoopStop 是否安全?

c# - 使用方法对数组的值求和

c# - 在辅助显示器上启动 WPF?

multithreading - 我可以确保 Haskell 执行原子 IO 吗?

c++ - Class 对象上的多线程

Java 可见性和同步 - Thinking in Java 示例

c# - 在 ASP.NET 中创建 Word 文档并返回给用户