如何在.NET 4.0中请求超时或取消之前“休眠”

时间:2013-09-10 09:21:08

标签: c# .net-4.0 sleep cancellation cancellationtokensource

在一段时间内睡觉的最佳方法是什么,但是IsCancellationRequested能够被CancellationToken打断?

我正在寻找一种适用于.NET 4.0的解决方案。

我想写

void MyFunc (CancellationToken ct)
{
   //... 
   // simulate some long lasting operation that should be cancelable 
   Thread.Sleep(TimeSpan.FromMilliseconds(10000), ct); 
}

5 个答案:

答案 0 :(得分:100)

我刚刚在这里写了博客:

CancellationToken and Thread.Sleep

简称:

var cancelled = token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));

在您的背景下:

void MyFunc (CancellationToken ct)
{
   //... 
   // simulate some long lasting operation that should be cancelable 
   var cancelled = ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
}

答案 1 :(得分:8)

或者,我认为这很清楚:

Task.Delay(waitTimeInMs, cancellationToken).Wait(cancellationToken);

答案 2 :(得分:3)

要在一定时间后取消异步操作,同时仍然可以手动取消操作,请使用以下内容

CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
cts.CancelAfter(5000);

这将在五秒后导致取消。要取消您自己的操作,您只需将token传递到异步方法并使用token.ThrowifCancellationRequested()方法,您可以在某处设置事件处理程序来触发cts.Cancel()

所以一个完整的例子是:

CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
cts.CancelAfter(5000);

// Set up the event handler on some button.
if (cancelSource != null)
{
    cancelHandler = delegate
    {
        Cancel(cts);
    };
    stopButton.Click -= cancelHandler;
    stopButton.Click += cancelHandler;
}

// Now launch the method.
SomeMethodAsync(token);

其中stopButton是您单击以取消正在运行的任务的按钮

private void Cancel(CancellationTokenSource cts)
{
    cts.Cancel();
}

,方法定义为

SomeMethodAsync(CancellationToken token)
{
    Task t = Task.Factory.StartNew(() => 
        {
            msTimeout = 5000;
            Pump(token);
        }, token,
           TaskCreationOptions.None,
           TaskScheduler.Default);
}

现在,为了让您能够使用该线程但还启用了用户取消,您需要编写一个“抽水”方法

int msTimeout;
bool timeLimitReached = false;
private void Pump(CancellationToken token)
{
    DateTime now = DateTime.Now;
    System.Timer t = new System.Timer(100);
    t.Elapsed -= t_Elapsed;
    t.Elapsed += t_Elapsed;
    t.Start();
    while(!timeLimitReached)
    {
        Thread.Sleep(250);
        token.ThrowIfCancellationRequested();
    }
}

void t_Elapsed(object sender, ElapsedEventArgs e)
{
    TimeSpan elapsed = DateTime.Now - this.readyUpInitialised;
    if (elapsed > msTimeout)
    {
        timeLimitReached = true;
        t.Stop();
        t.Dispose();
    }
}

注意,SomeAsyncMethod将返回调用者。要阻止呼叫者,您还必须在呼叫层次结构中向上移动Task

答案 3 :(得分:1)

我到目前为止找到的最佳解决方案是:

void MyFunc(CancellationToken ct)
{
  //...
  var timedOut = WaitHandle.WaitAny(new[] { ct.WaitHandle }, TimeSpan.FromMilliseconds(2000)) == WaitHandle.WaitTimeout;
  var cancelled = ! timedOut;
}

更新:

到目前为止,最好的解决方案是accepted answer

答案 4 :(得分:0)

在处理CancellationTokenSource之后访问CancellationToken.WaitHandle会引发异常:

  

ObjectDisposedException:CancellationTokenSource已被处置。

在某些情况下,尤其是在手动处置linked cancellation sources时(应该如此),这可能很麻烦。

此扩展方法允许“安全取消等待”;但是,它应与对取消令牌的状态和/或返回值的使用进行检查并正确标记一起使用。这是因为它禁止访问WaitHandle的异常,并且返回速度可能比预期的快。

internal static class CancellationTokenExtensions
{
    /// <summary>
    /// Wait up to a given duration for a token to be cancelled.
    /// Returns true if the token was cancelled within the duration
    /// or the underlying cancellation token source has been disposed.
    /// </summary>
    public static bool WaitForCancellation(this CancellationToken token, TimeSpan duration)
    {
        WaitHandle handle;
        try
        {
            handle = token.WaitHandle;
        }
        catch
        {
            // eg. CancellationTokenSource is disposed
            return true;
        }

        return handle.WaitOne(duration);
    }
}