码迷,mamicode.com
首页 > Windows程序 > 详细

[C#] 实现可设置超时的 Task

时间:2019-02-07 15:02:37      阅读:1020      评论:0      收藏:0      [点我收藏+]

标签:task   http   var   new   except   href   throw   ack   for   

前言

如何实现支持超时的 Task ?
关键点: Task.WhenAny

实现

一个扩展方法就可以搞定。

// 有返回值
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout)
{
    using (var timeoutCancellationTokenSource = new CancellationTokenSource())
    {
        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task)
        {
            timeoutCancellationTokenSource.Cancel();
            return await task;  // Very important in order to propagate exceptions
        }
        else
        {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}

// 无返回值
public static async Task TimeoutAfter(this Task task, TimeSpan timeout)
{
    using (var timeoutCancellationTokenSource = new CancellationTokenSource())
    {
        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task)
        {
            timeoutCancellationTokenSource.Cancel();
            await task;  // Very important in order to propagate exceptions
        }
        else
        {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}

参考

c# - Asynchronously wait for Task to complete with timeout - Stack Overflow

[C#] 实现可设置超时的 Task

标签:task   http   var   new   except   href   throw   ack   for   

原文地址:https://www.cnblogs.com/jasongrass/p/10354727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!