1.Wait usage
By default, Task is executed by an asynchronous thread in the thread pool. Whether the execution is completed can be judged by the Task's attribute IsCompleted,
If you want to perform subsequent main thread work after the sub-thread is completed, you can wait for the thread to complete by calling task.Wait(). After calling Wait, the current thread will be blocked until the sub-thread is completed.
Code example:
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.Wait sets the waiting time
static void Main(string[] args) { Task t = Task.Run(() => { Thread.Sleep(500); Console.WriteLine("Lance"); Thread.Sleep(500); }); Console.WriteLine("t.IsCompleted=" + t.IsCompleted); bool IsComplate= t.Wait(200); Console.WriteLine("wait 200毫秒后 t.IsCompleted=" + t.IsCompleted); Thread.Sleep(1000); Console.WriteLine("t.IsCompleted=" + t.IsCompleted); }
Running result:
The above is the detailed content of Task usage task waiting wait instance. For more information, please follow other related articles on the PHP Chinese website!