and then simultaneously:
task 2 waits for task 1, and then run after 4 seconds, so the event fired at the 6nd second.
taks 3 starts at the beginning, and fired at the 6nd second.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TestAsync
{
class Program
{
static void Main(string[] args)
{
var task1 = Task.Factory.StartNew(
() =>
{
Thread.Sleep(2000);
Console.WriteLine("Task 1 done!");
return 1;
});
var task2 = Task.Factory.StartNew(
async () =>
{
await task1;
Thread.Sleep(4000);
Console.WriteLine("Task 2 done!");
return 2;
});
var task3 = Task.Factory.StartNew(
() =>
{
Thread.Sleep(6000);
Console.WriteLine("Task 3 done!");
return 3;
});
var aTimer = new System.Timers.Timer();
aTimer.Interval = 100;
aTimer.Elapsed += (source, args) => { Console.Write("."); };
aTimer.AutoReset = true;
aTimer.Enabled = true;
Task.WhenAll(task1, task2, task3).ContinueWith(results =>
{
aTimer.Enabled = false;
int result = task1.Result + task2.Result.Result + task3.Result;
Console.WriteLine($"result: {result}");
});
Console.ReadLine();
}
}
}


No comments:
Post a Comment