C # learning how to process multiple threads in a Task class

Source: Internet
Author: User

1. Define a thread
Var task1 = Task. Factory. StartNew () => DoSomeWork ());
The method is as follows:
View Code
Private static object DoSomeWork ()
{
Console. WriteLine ("nihao ");
System. Threading. Thread. Sleep (3000 );
Console. Write ("nihao ");
Return "xiexie ";
}

2. execute another method after multi-thread execution
Var task1 = Task. Factory. StartNew () => DoSomeWork (). ContinueWith (
Task =>{ Console. WriteLine (task. Result. ToString () ;}). ContinueWith (
Task =>{ Console. WriteLine (task. Result. ToString ());});
3. Wait for all threads to end
Var task1 = Task. Factory. StartNew () => DoSomeWork ());
Var task2 = Task. Factory. StartNew () => DoSomeWork ());
Var task3 = Task. Factory. StartNew () => DoSomeWork ());
Task. WaitAll (task1, task2, task3 );
4. Wait until one of the threads ends.
Var task1 = Task. Factory. StartNew () => DoSomeWork ());
Var task2 = Task. Factory. StartNew () => DoSomeWork ());
Var task3 = Task. Factory. StartNew () => DoSomeWork ());
Task. WaitAny (task1, task2, task3 );
5. Method for waiting for all threads to end execution
Var task1 = Task. Factory. StartNew () =>
{
Thread. Sleep (3000 );
Return "dummy value 1 ";
});
 
Var task2 = Task. Factory. StartNew () =>
{
Thread. Sleep (3000 );
Return "dummy value 2 ";
});
 
Var task3 = Task. Factory. StartNew () =>
{
Thread. Sleep (3000 );
Return "dummy value 3 ";
});
 
Task. Factory. ContinueWhenAll (new [] {task1, task2, task3}, tasks =>
{
Foreach (Task <string> task in tasks)
{
Console. WriteLine (task. Result );
}
});
 

From unlimited imagination

Related Article

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.