Here is some of my code:
var tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(TimeSpan.FromSeconds(30));
response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, tokenSource.Token);
response.EnsureSuccessStatusCode();
using (var readStream = await response.Content.ReadAsStreamAsync())
{
var buffer = new byte[4096];
var length = 0;
while ((length = await readStream.ReadAsync(buffer, 0, buffer.Length, tokenSource.Token)) != 0)
{
//...
if (waitTime)
await Task.Delay(waitTime, tokenSource.Token);
}
}
Can I use the CancellationToken like that? Or is that the correct way to write it?
CodePudding user response:
Yes, it's normal to create a token source once and then have a tree of methods take the token and use it for cancellation.