-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCancellationDemo.cs
More file actions
36 lines (30 loc) · 1.12 KB
/
Copy pathCancellationDemo.cs
File metadata and controls
36 lines (30 loc) · 1.12 KB
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
namespace ConcurrencyLab;
internal static class CancellationDemo
{
public static async Task RunAsync()
{
Console.WriteLine("\n3) CANCELLATION — request, observe, stop safely");
using var cancellationSource =
new CancellationTokenSource(TimeSpan.FromMilliseconds(650));
try
{
await ProcessOrderAsync(cancellationSource.Token);
}
catch (OperationCanceledException)
when (cancellationSource.IsCancellationRequested)
{
Console.WriteLine(" Caller observed the expected cancelled outcome.");
}
}
private static async Task ProcessOrderAsync(CancellationToken cancellationToken)
{
for (int step = 1; step <= 10; step++)
{
// Real APIs such as HttpClient and EF Core also accept the token.
await Task.Delay(150, cancellationToken);
// Useful in CPU loops; it throws OperationCanceledException when signalled.
cancellationToken.ThrowIfCancellationRequested();
Console.WriteLine($" completed order step {step}/10");
}
}
}