如何“睡觉”?直到在.NET 4.0中请求超时或取消 [英] How to "sleep" until timeout or cancellation is requested in .NET 4.0

查看:139
本文介绍了如何“睡觉”?直到在.NET 4.0中请求超时或取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好的睡眠时间是什么,但是可以被 CancellationToken IsCancellationRequested 打断$ c>?

What's the best way to sleep a certain amount of time, but be able to be interrupted by a IsCancellationRequested from a CancellationToken?

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

I'm looking for a solution which works in .NET 4.0.

I' d想写

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


推荐答案

我只是在这里写博客:

CancellationToken和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));
}

这篇关于如何“睡觉”?直到在.NET 4.0中请求超时或取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆