Friday, June 17, 2016

C# run jobs (Task) on multiple threads, return upon completion of the first one

class Program
{
static void Main(string[] args)
{
Test();
Console.ReadKey();
}

static async void Test()
{
int result = await TaskTest();
Console.WriteLine(result);
}
static async Task<int> TaskTest()
{
Task<int> task1 = new Task<int>(() => { Thread.Sleep(1000); return 1; });
Task<int> task2 = new Task<int>(() => { Thread.Sleep(50); return 2; });
task1.Start();
task2.Start();
var multiTaskResult = await Task.WhenAny(task1, task2);
return multiTaskResult.Result;
}
}