.Net6 新特性 - 轻松设置异步任务的超时
如果超时会抛出 “TimeoutException”
Task operationTask = DoSomethingLongAsync();
await operationTask.WaitAsync(TimeSpan.FromSeconds(5));
async Task DoSomethingLongAsync()
{
Console.WriteLine("DoSomethingLongAsync started.");
await Task.Delay(TimeSpan.FromSeconds(10));
Console.WriteLine("DoSomethingLongAsync ended.");
}
// Output:
// DoSomethingLongAsync started.
// Unhandled exception.System.TimeoutException: The operation has timed out.**