如何与QUOT;睡眠"直到超时或取消请求在C#4.0 [英] How to "sleep" until timeout or cancellation is requested in C#4.0

查看:278
本文介绍了如何与QUOT;睡眠"直到超时或取消请求在C#4.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是睡眠一定的时间的最好方式,但可以通过中断一个 IsCancellationRequested 的CancellationToken



我在寻找一种解决方案,在C#4.0。



我想写

 无效MYFUNC(CT的CancellationToken)
{
// ...
//模拟一些持久的操作,应该是取消
的Thread.Sleep(TimeSpan.FromMilliseconds(10000),CT);
}


解决方案

我只是在博客在这里



的CancellationToken和Thread.sleep代码



在短:

  VAR取消=令牌。 WaitHandle.WaitOne(TimeSpan.FromSeconds(5)); 

在上下文:

 无效MYFUNC(CT的CancellationToken)
{
// ...
//模拟一些持久的操作,应该是取消
VAR取消=克拉.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
}


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

I'm looking for a solution working in C#4.0.

I'd like to write

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

解决方案

I just blogged about it here:

CancellationToken and Thread.Sleep

in Short:

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

In your context:

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

这篇关于如何与QUOT;睡眠"直到超时或取消请求在C#4.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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