Last active
April 15, 2022 02:26
-
-
Save guitarrapc/edcdee40f2227cd49a6a378c730727fa to your computer and use it in GitHub Desktop.
C# CancellatonSource Status when Cancel on cts or LinkedCancellationSource.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cancel on Source CancellationTokenSource | |
async Task Main() | |
{ | |
using var cts = new CancellationTokenSource(); | |
var ct = cts.Token; | |
var task = FooAsync(ct); | |
await Task.Delay(TimeSpan.FromSeconds(3)); | |
cts.Cancel(); | |
cts.Dump("cts"); // IsCancellationRequested True | |
} | |
public async Task FooAsync(CancellationToken ct) | |
{ | |
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct); | |
var linkedCt = linkedCts.Token; | |
var i = 0; | |
var interval = TimeSpan.FromSeconds(1); | |
while (!linkedCt.IsCancellationRequested) | |
{ | |
await Task.Delay(interval); | |
await Task.WhenAll(new[] {DoAsync(linkedCt), DoAsync(linkedCt)}); | |
i++; | |
} | |
linkedCts.Dump("linked cts"); // IsCancellationRequested True | |
} | |
public async Task DoAsync(CancellationToken ct) | |
{ | |
try | |
{ | |
using var client = new HttpClient(); | |
var result = await client.GetAsync("https://tech.guitarrapc.com", ct); | |
result.StatusCode.Dump(); | |
} | |
catch (OperationCanceledException cex) | |
{ | |
cex.Dump(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cancel on LinkedCancellationTokenSource | |
async Task Main() | |
{ | |
using var cts = new CancellationTokenSource(); | |
var ct = cts.Token; | |
await FooAsync(ct); | |
cts.Dump("cts"); // IsCancellationRequested False | |
} | |
public async Task FooAsync(CancellationToken ct) | |
{ | |
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct); | |
var linkedCt = linkedCts.Token; | |
var i = 0; | |
var interval = TimeSpan.FromSeconds(1); | |
while (!linkedCt.IsCancellationRequested) | |
{ | |
await Task.Delay(interval); | |
var task = Task.WhenAll(new[] { DoAsync(linkedCt), DoAsync(linkedCt) }); | |
if (i++ >= 2) | |
{ | |
linkedCts.Cancel(); | |
} | |
await task; | |
} | |
linkedCts.Dump("linked cts"); // IsCancellationRequested True | |
} | |
public async Task DoAsync(CancellationToken ct) | |
{ | |
try | |
{ | |
using var client = new HttpClient(); | |
var result = await client.GetAsync("https://tech.guitarrapc.com", ct); | |
result.StatusCode.Dump(); | |
} | |
catch (OperationCanceledException cex) | |
{ | |
cex.Dump(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment