gpt4 book ai didi

c# - 延迟任务开始的正确方法

转载 作者:IT王子 更新时间:2023-10-29 03:48:31 33 4
gpt4 key购买 nike

我想安排一个任务在 x 毫秒后开始,并能够在它开始之前(或刚好在任务开始时)取消它。

第一次尝试是这样的

var _cancelationTokenSource = new CancellationTokenSource();

var token = _cancelationTokenSource.Token;
Task.Factory.StartNew(() =>
{
token.ThrowIfCancellationRequested();
Thread.Sleep(100);
token.ThrowIfCancellationRequested();
}).ContinueWith(t =>
{
token.ThrowIfCancellationRequested();
DoWork();
token.ThrowIfCancellationRequested();
}, token);

但我觉得应该有更好的方法,因为这会在 sleep 时用完一个线程,在此期间它可以被取消。

我还有哪些其他选择?

最佳答案

Damien_The_Unbeliever mentioned ,异步 CTP 包括 Task.Delay。幸运的是,我们有 Reflector:

public static class TaskEx
{
static readonly Task _sPreCompletedTask = GetCompletedTask();
static readonly Task _sPreCanceledTask = GetPreCanceledTask();

public static Task Delay(int dueTimeMs, CancellationToken cancellationToken)
{
if (dueTimeMs < -1)
throw new ArgumentOutOfRangeException("dueTimeMs", "Invalid due time");
if (cancellationToken.IsCancellationRequested)
return _sPreCanceledTask;
if (dueTimeMs == 0)
return _sPreCompletedTask;

var tcs = new TaskCompletionSource<object>();
var ctr = new CancellationTokenRegistration();
var timer = new Timer(delegate(object self)
{
ctr.Dispose();
((Timer)self).Dispose();
tcs.TrySetResult(null);
});
if (cancellationToken.CanBeCanceled)
ctr = cancellationToken.Register(delegate
{
timer.Dispose();
tcs.TrySetCanceled();
});

timer.Change(dueTimeMs, -1);
return tcs.Task;
}

private static Task GetPreCanceledTask()
{
var source = new TaskCompletionSource<object>();
source.TrySetCanceled();
return source.Task;
}

private static Task GetCompletedTask()
{
var source = new TaskCompletionSource<object>();
source.TrySetResult(null);
return source.Task;
}
}

关于c# - 延迟任务开始的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4990602/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com