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.");
}
}
}