当前位置 : 主页 > 编程语言 > c语言 >

2019-8-28测试代码

来源:互联网 收集:自由互联 发布时间:2021-06-25
2019-8-28测试代码 测试 C# 代码块 // 有返回值 public static async TaskTResult TimeoutAfterTResult( this TaskTResult task, TimeSpan timeout){ using (var timeoutCancellationTokenSource = new CancellationTokenSource()) { var comple

2019-8-28测试代码

测试 C# 代码块
// 有返回值
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.");
        }
    }
}
网友评论