Task usage (2)-wait for wait and taskwait
1. Wait usageBy default, a Task has asynchronous thread execution in the thread pool. To determine whether the execution is complete, you can use the IsCompleted attribute of the Task, you can call a task to perform subsequent operations on the main thread. wait for the thread to complete. After Wait is called, the current thread will be blocked until the sub-thread completes. Sample Code:
static void Main(string[] args) { Task t = Task.Run(() => { Thread.Sleep(500); Console.WriteLine("Lance"); Thread.Sleep(500); }); Console.WriteLine("t.IsCompleted=" + t.IsCompleted); t.Wait(); Console.WriteLine("t.IsCompleted=" + t.IsCompleted); }
Running result:
2. Set the Wait time for Wait.
Static void Main (string [] args) {Task t = Task. run () => {Thread. sleep (1, 500); Console. writeLine ("Lance"); Thread. sleep (500) ;}); Console. writeLine ("t. isCompleted = "+ t. isCompleted); bool IsComplate = t. wait (200); Console. writeLine ("wait 200 ms later t. isCompleted = "+ t. isCompleted); Thread. sleep (1, 1000); Console. writeLine ("t. isCompleted = "+ t. isCompleted );}
Running result: