Processing math: 100%

Sunday, December 22, 2019

JavaScript's new Promise and Promise.all counterpart in C#

The result starts with:
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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