Skip to content

Instantly share code, notes, and snippets.

@winuxue
Created December 26, 2019 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save winuxue/e7ba871eacd53910a885bf96b45ef83f to your computer and use it in GitHub Desktop.
Save winuxue/e7ba871eacd53910a885bf96b45ef83f to your computer and use it in GitHub Desktop.
Executing Parallel Tasks in c# example
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