永远不会结束,直到取消任务要求 [英] A task that will never end until cancellation is requested
问题描述
我需要的,永远不会结束,直到取消请求的任务。目前做到这一点最简单的方法是:
I need a task that never ends until cancellation is requested. At the moment the simplest way to do that is:
var cancellation = new CancellationTokenSource();
var task = Task.Factory.StartNew(async () =>
{
while (true)
{
await Task.Delay(10000, cancellation.Token);
}
}, cancellation.Token).Unwrap();
我不喜欢的是调用 Task.Delay
的方法,因为它需要有限的时间间隔等。
What I don't like is a call to Task.Delay
method because it requires limited time interval for waiting.
有没有更好的解决方案?
Is there more elegant solution?
推荐答案
作为替代 TaskCompletionSource
与 token.Register
,这里有一些单行:
As an alternative to TaskCompletionSource
with token.Register
, here are some one-liners:
var task = new Task(() => {}, token); // don't do task.Run()!
或者简单:
var task = Task.Delay(Timeout.Infinite, token);
有一个在<一个连一个很好的优化 Timeout.Infinite
href="http://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs#5fb80297e082b8d6"相对=nofollow>电流 Task.Delay
实施。
There's even a nice optimization for Timeout.Infinite
in the current Task.Delay
implementation.
这篇关于永远不会结束,直到取消任务要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!