Home > Net >  Call the third party time consuming method to cancel the Task
Call the third party time consuming method to cancel the Task

Time:03-12

Consult, Task. The run () there is a time consuming method of the third party can't use cancellationToken judge cancel, after more than a certain of time, there are other ways to terminate or abnormal return?

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 Task TimeoutAfter (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
  •  Tags:  
  • C#
  • Related