CodePudding user response:
If a soldier was ordered "silent 30 minutes, and then in the 15th minute, to make him stop silent, there is no effective method, because the silent period can't response to external commands,CodePudding user response:
//returns a value
Public static async TaskTimeoutAfter (this Task The task, the 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
}
The else
{
Throw new TimeoutException (" The operation has timed out. ");
}
}
}
//there is no return value
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 the task;//Very important in order to propagate exceptions
}
The else
{
Throw new TimeoutException (" The operation has timed out. ");
}
}
}
CodePudding user response:
Can only like the second floor in the context of the currently used WhenAny to implement, but behind the abnormal time-consuming task might have been running, unable to monitor