-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathCancellationTokenExample.cs
64 lines (54 loc) · 2.07 KB
/
CancellationTokenExample.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 CancellationTokenExample
{
static readonly Random Random = new Random();
static readonly CancellationTokenSource cancelationSource = new CancellationTokenSource();
public static void Run()
{
Console.WriteLine("Cancelation Token example.");
var stringBuilder = new StringBuilder();
var h = new Task(() => AddSymbol(stringBuilder, 'H'), cancelationSource.Token);
var e = new Task(() => AddSymbol(stringBuilder, 'e'), cancelationSource.Token);
var l = new Task(() => AddSymbol(stringBuilder, 'l'), cancelationSource.Token);
var o = new Task(() => AddSymbol(stringBuilder, 'o'), cancelationSource.Token);
Console.WriteLine("Press enter to stop execution");
h.Start();
var promise = h.Then(e)
.Then(l)
.Then(new Task(() => AddSymbol(stringBuilder, 'l')))
.Then(o);
Console.ReadLine();
//Throw cancel request
cancelationSource.Cancel();
try
{
//wait when all threads will be stopped
promise.Wait(cancelationSource.Token);
}
catch (OperationCanceledException ex)
{
//it's expected exception
}
finally
{
Console.WriteLine("Result: {0}", stringBuilder);
Console.ReadLine();
}
}
public static void AddSymbol(StringBuilder stringBuilder,
char symbol)
{
//1-3 second
Thread.Sleep(Random.Next(1000, 3000));
//Check if cancellation was requested
cancelationSource.Token.ThrowIfCancellationRequested();
stringBuilder.Append(symbol);
Console.WriteLine("Appended '{0}' symbol", symbol);
}
}
}