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: