如何“睡觉”?直到在.NET 4.0中请求超时或取消

编程入门 行业动态 更新时间:2024-10-23 08:24:40
本文介绍了如何“睡觉”?直到在.NET 4.0中请求超时或取消的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最好的睡眠时间是什么,但是可以被 CancellationToken

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中请求超时或取消

本文发布于:2023-11-10 09:41:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575029.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!