永远不会结束,直到取消任务要求永远不会、任务、结束

2023-09-03 01:27:17 作者:能量尐女

我需要的,永远不会结束,直到取消请求的任务。目前做到这一点最简单的方法是:

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);

有一个在电流 Task.Delay 实施。

There's even a nice optimization for Timeout.Infinite in the current Task.Delay implementation.