Task usage (2)-wait for wait and taskwait

Source: Internet
Author: User

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:

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.