Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active April 15, 2022 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/edcdee40f2227cd49a6a378c730727fa to your computer and use it in GitHub Desktop.
Save guitarrapc/edcdee40f2227cd49a6a378c730727fa to your computer and use it in GitHub Desktop.
C# CancellatonSource Status when Cancel on cts or LinkedCancellationSource.
// 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();
}
}
// 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