取消.Net 4.0中的任务延迟

编程入门 行业动态 更新时间:2024-10-25 22:33:42
本文介绍了取消.Net 4.0中的任务延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在尝试在必须以.Net 4.0为目标的程序中替代.Net 4.5的 Task.Delay()方法。我在此博客中找到了以下代码。

I am currently trying to implement a substitute for .Net 4.5's Task.Delay() method in a program that must target .Net 4.0. I found the following code at this blog.

/* You can write Task-based asynchronous methods by utilizing a TaskCompletionSource. A TaskCompletionSource gives you a 'slave' Task that you can manually signal. Calling SetResult() signals the task as complete, and any continuations kick off. */ void Main() { for (int i = 0; i < 10000; i++) { Task task = Delay (2000); task.ContinueWith (_ => "Done".Dump()); } } Task Delay (int milliseconds) // Asynchronous NON-BLOCKING method { var tcs = new TaskCompletionSource<object>(); new Timer (_ => tcs.SetResult (null)).Change (milliseconds, -1); return tcs.Task; }

任务相当对我来说是新的。 System.Threading.Timer 和 TaskCompletionSource 对我来说是全新的(到目前为止),我正在努力咬他们。除此之外,我想知道如何在此代码中添加 CancellationToken 功能。我假设我可以像这样向 Delay()方法添加参数:

Tasks are fairly new to me. System.Threading.Timer and TaskCompletionSource are brand new to me (as of today), and I'm struggling a bit with them. All that aside, I'm wondering how I might add CancellationToken functionality to this code. I'm assuming I could add a parameter to the Delay() method like this:

Task Delay (int milliseconds, CancellationToken token) // Asynchronous NON-BLOCKING method { var tcs = new TaskCompletionSource<object>(); new Timer (_ => tcs.SetResult (null)).Change (milliseconds, -1); return tcs.Task; }

...但是,在哪里放置检查令牌的逻辑并摆脱方法?回调中的某处?这有可能吗?

... but then, where do I put the logic for checking the token and getting out of the method? Somewhere in the callback? Is this even possible?

推荐答案

我试图尽可能少地更改您的代码,但这是一个工作示例,其行为与Task.Delay。

I've tried to change your code as little as possible but here is a working example that behaves in the same way as Task.Delay.

请务必注意,我使用了 TrySetCanceled 和 TrySetResult 因为计时器可以在取消任务后完成。理想情况下,您想停止计时器。

It's important to note that I use TrySetCanceled and TrySetResult because the Timer could finish after the task is canceled. Ideally you want to stop the timer.

还请注意,已取消的任务将引发 TaskCanceledException

Also note a canceled task will throw a TaskCanceledException

static void Main(string[] args) { // A cancellation source that will cancel itself after 1 second var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)); try { // This will only wait 1 second because as it will be cancelled. Task t = Delay(5000, cancellationTokenSource.Token); t.Wait(); Console.WriteLine("The task completed"); } catch (AggregateException exception) { // Expecting a TaskCanceledException foreach (Exception ex in exception.InnerExceptions) Console.WriteLine("Exception: {0}", ex.Message); } Console.WriteLine("Done"); Console.ReadLine(); } private static Task Delay(int milliseconds, CancellationToken token) { var tcs = new TaskCompletionSource<object>(); token.Register(() => tcs.TrySetCanceled()); Timer timer = new Timer(_ => tcs.TrySetResult(null)); timer.Change(milliseconds, -1); return tcs.Task; }

多读一些问题。如果您需要Task.Delay并且以.NET 4.0为目标,则应使用 www.nuget/packages/Microsoft.Bcl.Async/ 包含方法 TaskEx.Delay

Reading a bit more into your question. If you need Task.Delay and you're targeting .NET 4.0 then you should use the Microsoft Async nuget package from www.nuget/packages/Microsoft.Bcl.Async/ it contains the method TaskEx.Delay

更多推荐

取消.Net 4.0中的任务延迟

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

发布评论

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

>www.elefans.com

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