Reporting progress during asynchronous method execution you can use the progress<t> type, create an instance of the Progress<t> type, and add a report event to it as a parameter in the Async method. On the code:
We need to invoke the Async method:
1 /// <summary>2 ///asynchronous tasks that report progress and can be canceled3 /// </summary>4 /// <param name= "token" ></param>5 /// <param name= "Progress" ></param>6 /// <returns></returns>7 Public Static AsyncTask Progressasync (CancellationToken token, iprogress<Double> progress =NULL)8 {9 DoublePercentComplete =0;Ten //loop execution when progress does not reach 100%, simulating a long-executed task One while(percentcomplete<= -) A { - //Judging Cancellation token - if(token.) iscancellationrequested) the return; - //report to Caller -Progress?. Report (PercentComplete); - awaitTask.delay (Timespan.fromseconds (1)); +PercentComplete + =Ten; - } +}
Call Method:
1 Static ReadOnlyCancellationTokenSource Token =NewCancellationTokenSource ();2 3 /// <summary>4 ///methods to invoke report progress5 /// </summary>6 /// <returns></returns>7 Private Async StaticTask progresstest () {8 //creating an Progress instance9 varprogress=Newprogress<Double>();Ten //Response Events When adding a report OneProgress. ProgressChanged + = (sender, args) = A { -Console.WriteLine ($"Current Progress {args}%"); - }; the //Invoke Report Method - awaitCharpt1.Charpt1.ProgressAsync (Token.token, progress); -}
The main method to execute is as follows:
1 Static voidMain (string[] args)2 {3 progresstest ();4 varKey =Console.readkey ();5 //Cancel task When input character is J6 if(Key. KeyChar = ='J')7 {8 Token.cancel ();9Console.WriteLine ("The task was canceled! ");Ten } One console.readline (); A}
When we do not cancel the task, we can see the following results
Enter ' j ' during execution to cancel the task with the following results:
[C # Concurrent Programming Learning Note].net execution progress in asynchronous operation execution and canceling asynchronous operations