如何取消线程? [英] How to Cancel a Thread?

查看:138
本文介绍了如何取消线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的BackgroundWorker 的情况下,事件处理程序 - 在的DoWork 物业 - ,取消可以通过 e.Cancel 报道。

In case of BackgroundWorker, a cancel can be reported by the e.Cancel - property of the DoWork - event handler.

我如何能实现同样的事情用的 对象?

How can I achieve the same thing with a Thread object?

推荐答案

下面。是这样做的一种方式的完整的例子

Here is a full example of one way of doing it.

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.");    
}

在短;线程检查一个布尔标志,只要该标志为真正乳宁不断。我更喜欢这种方法调用超过 Thread.Abort的监守似乎有点更好和更清洁。

In short; the thread checks a bool flag, and keeps runing as long as the flag is true. I prefer this approach over calling Thread.Abort becuase it seems a bit nicer and cleaner.

这篇关于如何取消线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆