Home > Net >  If a method can't incoming CancellationToken, so is there a way to stop it
If a method can't incoming CancellationToken, so is there a way to stop it

Time:11-28

This is a test code, the real business, LoopAsync is a file upload method, cannot pass CancellationToken, sometimes takes a long time, want to force to stop and stop, consult,
 
The static void Main (string [] args)
{
Var timeoutCancellationTokenSource=new CancellationTokenSource ();
DateTime currentDate=DateTime. Now;
Console. WriteLine ($" beginning of the test: {currentDate: yyyyMMdd HH: mm: ss} ");
Try
{
_=Task. Run (()=& gt;
{
For (int I=0; I & lt; 3; I++)
{
Console. WriteLine ($" Cancel the countdown: {I} ");
Task. Delay (1000). The Wait ();
}
TimeoutCancellationTokenSource. Cancel ();
});
Var task=LoopAsync (/* timeoutCancellationTokenSource. Token */);
Task. Wait (6 * 1000);
}
The catch (Exception ex)
{
Console. WriteLine ($" test error: {ex. Message} ");
}
The finally
{
Console. WriteLine ($" end of the test, available: {(DateTime. Now - currentDate). TotalSeconds} ");
Console.ReadLine();
}
}

///& lt; Summary>
///if you can't into CancellationToken here, so what are the way to stop the task
///& lt;/summary>
///& lt; Returns>
Public static async Task LoopAsync (/* CancellationToken token=default */)
{
For (int I=0; I & lt; 10000; I++)
{
//if (token. IsCancellationRequested)
//{
//the Console. WriteLine ($" LoopAsync: IsCancellationRequested ");
//return;
//}
Console. WriteLine ($" LoopAsync: I={I} ");
Await Task. Delay (1000);
}
return;
}

CodePudding user response:

You see,
https://www.cnblogs.com/hanjun0612/p/11233525.html

CodePudding user response:

reference 1st floor is nu month god reply:
you see,
https://www.cnblogs.com/hanjun0612/p/11233525.html

LoopAsync is a third party to receive incoming Token to stop, also have no a ManualResetEvent to suspend,
Feel this link inside operation, is I understand is wrong?
  •  Tags:  
  • C#
  • Related