经典永不落幕使用任务线程循环? [英] Classic never-ending thread loop using tasks?

查看:216
本文介绍了经典永不落幕使用任务线程循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于是一个很常见的线程的场景:

Given is a very common threading scenario:

宣言

private Thread _thread;
private bool _isRunning = false;

开始

_thread = new Thread(() => NeverEndingProc());
thread.Start();

方法

private void NeverEndingProc() {
    while(_isRunning) {
        do();
    }
}

可能在直到它得到通过让线程用完( _isRunning = FALSE )。

现在我想知道:是否有可能做工作是一回事吗?使用的CancellationToken ?或者是工作唯一对于那些有望结束和程序报告状态?

Now I'm wondering: Is it possible to do the same thing with Task? Using a CancellationToken? Or are Tasks only for procedures that are expected to end and report status?

推荐答案

您的可以的肯定只是路过 NeverEndingProc 到<$ C做到这一点$ C> Task.Run 。

You can certainly do this just by passing NeverEndingProc to Task.Run.

然而,在功能上有一个​​重要的区别:如果一个异常在裸主题传播出去 NeverEndingProc ,它会崩溃的过程。如果是在工作,这将提高 TaskScheduler.UnobservedException ,然后被忽略不计(截至.NET 4.5 )。

However, there is one important difference in functionality: if an exception is propagated out of NeverEndingProc in a bare Thread, it will crash the process. If it is in a Task, it will raise TaskScheduler.UnobservedException and then be silently ignored (as of .NET 4.5).

这是说,有一个你可以探索的替代品。 反应的扩展,例如,pretty多少消除任何需要无限线程循环。

That said, there are alternatives you can explore. Reactive Extensions, for example, pretty much removes any need for the "infinite thread loop".

这篇关于经典永不落幕使用任务线程循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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