Understand C # task, asynchronously and wait
C # task
A task class is an asynchronous shell of a task. Thread.Sleep (1000) can stop a thread running for 1 second. Although Task.Delay (1000) will not stop the current operation. See Code:
public static void Main(string[] args){ TaskTest(); } private static void TaskTest(){ Task.Delay(5000); System.Console.WriteLine("task done"); }
When you start, "job completed" will be displayed immediately. Therefore, I can assume that each method from Task should be asynchronous. If I replace TaskTest () with Task.Run (() => TaskTest ()), the completed task will not be displayed at all until I add the console. ReadLine (); after the Run method.
Internally, the Task class represents the state of a thread in a state machine. Each state in the state machine has several states, such as “Start”, “Delay”, “Cancel” and “Stop”.
asynchronous and pending
Now you may wonder if all tasks are asynchronous, what is the purpose of Task.Delay? next, let it really delay the current thread using async and wait
public static void Main(string[] args){ TaskTest(); System.Console.WriteLine("main thread is not blocked"); Console.ReadLine(); } private static async void TaskTest(){ await Task.Delay(5000); System.Console.WriteLine("task done"); }
async tell caller, I'm an asynchronous method, don't wait for me. waiting inside TaskTest () requires waiting for an asynchronous task. Now, after starting, the program will wait 5 seconds to display the completed text.
Cancel task
Since Task is a state machine, there must be a way to cancel the task while the task is executing.
static CancellationTokenSource tokenSource = new CancellationTokenSource(); public static void Main(string[] args){ TaskTest(); System.Console.WriteLine("main thread is not blocked"); var input=Console.ReadLine(); if(input=="stop"){ tokenSource.Cancel(); System.Console.WriteLine("task stopped"); } Console.ReadLine(); } private static async void TaskTest(){ try{ await Task.Delay(5000,tokenSource.Token); }catch(TaskCanceledException e){
Now that the program is running, you can enter “stop” to cancel the “Delay” task.
Andrew Zhu Sep 08 '16 at 3:37 2016-09-08 03:37
source share