是否可以使用System.Threading.Task.Task创建可以取消的任务循环?
该流程应从Task.Delay(x ms)开始,然后继续用户定义的任务,然后是另一个Task.Delay(y ms),然后从用户定义的任务重复。
var result = Task.Delay(initialDelay)
.ContinueWith(t => dostuff..)
.ContinueWith what goes here?
使用任务甚至可行吗?
我可以启动一个计时器并完成它,但是如果需要取消,使用任务似乎是正确的方法,不是吗?
await
使这个超级容易:
public async Task TimedLoop(Action action,
CancellationToken token, TimeSpan delay)
{
while (true)
{
token.ThrowIfCancellationRequested();
action();
await Task.Delay(delay, token);
}
}
如果没有async
(但仍仅使用TPL),则有点麻烦。我通常通过将自己附加到类型变量上的延续来解决此问题Task
。这可以正常工作,但是可能需要花一秒钟的时间才能将其缠绕在头上。没有await
它,使用aTimer
代替可能会更容易。
public Task TimedLoop(Action action,
CancellationToken token, TimeSpan delay)
{
//You can omit these two lines if you want the method to be void.
var tcs = new TaskCompletionSource<bool>();
token.Register(() => tcs.SetCanceled());
Task previous = Task.FromResult(true);
Action<Task> continuation = null;
continuation = t =>
{
previous = previous.ContinueWith(t2 => action(), token)
.ContinueWith(t2 => Task.Delay(delay, token), token)
.Unwrap()
.ContinueWith(t2 => previous.ContinueWith(continuation, token));
};
previous.ContinueWith(continuation, token);
return tcs.Task;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句