Created
December 26, 2019 22:30
-
-
Save winuxue/e7ba871eacd53910a885bf96b45ef83f to your computer and use it in GitHub Desktop.
Executing Parallel Tasks in c# example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using System.Threading; | |
using System.Collections.Generic; | |
namespace parallel_tasks | |
{ | |
class Program | |
{ | |
static async Task Main(string[] args) | |
{ | |
var tasks = new List<Task<string>> | |
{ | |
Task.Run(() => doStuff("Task 0", 700)), | |
Task.Run(() => doStuff("Task 1", 300)), | |
Task.Run(() => doStuff("Task 2", 500)) | |
}; | |
var task = await Task.WhenAny(tasks.ToArray()); | |
Console.WriteLine(task.Result + " completed"); | |
} | |
static string doStuff(string strName, int milliseconds) | |
{ | |
for (int i = 1; i <= 3; i++) | |
{ | |
// Thread.Yield(); | |
Thread.Sleep(milliseconds); | |
Console.WriteLine(strName + ": " + i.ToString()); | |
} | |
return strName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment