-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathSequentialExecutionExample.cs
64 lines (51 loc) · 1.95 KB
/
SequentialExecutionExample.cs
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
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncAndPromises
{
public class SequentialExecutionExample
{
static readonly Random Random = new Random();
public static void SequentialPromiseExample()
{
var stringBuilder = new StringBuilder();
var h = new Task(() => AddSymbol(stringBuilder, 'H'));
var e = new Task(() => AddSymbol(stringBuilder, 'e'));
var l = new Task(() => AddSymbol(stringBuilder, 'l'));
var o = new Task(() => AddSymbol(stringBuilder, 'o'));
//Functions will be executed in order as it was specified
h.Start();
var promise = h.Then(e)
.Then(l)
.Then(new Task(() => AddSymbol(stringBuilder, 'l')))
.Then(o);
promise.Wait();
Console.WriteLine(stringBuilder.ToString());
Console.ReadLine();
}
public static void SequentialPromiseExampleImprovedSyntax()
{
var stringBuilder = new StringBuilder();
Action h = () => { AddSymbol(stringBuilder, 'H'); };
Action e = () => { AddSymbol(stringBuilder, 'e'); };
Action l = () => { AddSymbol(stringBuilder, 'l'); };
Action o = () => { AddSymbol(stringBuilder, 'o'); };
var promise = h.Then(e);
promise = promise.Then(l)
.Then(l)
.Then(o);
promise.Wait();
Console.WriteLine(stringBuilder.ToString());
Console.ReadLine();
}
public static void AddSymbol(StringBuilder stringBuilder,
char symbol)
{
//1-3 seconds
Thread.Sleep(Random.Next(1000, 3000));
stringBuilder.Append(symbol);
Console.WriteLine("Appended '{0}' symbol", symbol);
}
}
}