Home > Backend Development > C#.Net Tutorial > Task usage task waiting wait instance

Task usage task waiting wait instance

零下一度
Release: 2018-05-18 16:10:36
Original
12343 people have browsed it

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);
        }
Copy after login

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);
        }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template