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