0

CancellationTokenSource seems to be ignoring the time for the loop operation. It takes a while to iterate over it and I have the limit set to 500ms but it's ignoring it. What could I be doing wrong?

static async Task<int> Thread1()
{
  CancellationTokenSource source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromMilliseconds(500));
  return await Task.Run(async () =>
  {
    using (var client = new HttpClient())
    {          
      var site = await client.GetAsync("http://webcode.me", source.Token);
      for (int i = 0; i < 10000000; i++)
      {
        Console.WriteLine(i);
      }
      string content = await site.Content.ReadAsStringAsync();
      return content.Count(x => x == 'e');
    }
  }, source.Token);
}
Wes
  • 1,847
  • 1
  • 16
  • 30

1 Answers1

0

You're never checking for cancellation in your loop.

Call the following in your loop:

https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken.throwifcancellationrequested?view=netframework-4.8

e.g.

token.ThrowIfCancellationRequested(); 

which is equal to:

if (token.IsCancellationRequested)   
    throw new OperationCanceledException(token);  
sommmen
  • 6,570
  • 2
  • 30
  • 51
  • There is no way to pass a token to [`HttpContent.ReadAsStringAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.readasstringasync). – Theodor Zoulias Apr 11 '20 at 08:44
  • It would be ideal for you to post the code in the answer and avoid linking externally as an important part of your answer. – Enigmativity Apr 14 '20 at 03:13
  • @Enigmativity i get that but a) its just one method b) its on msdn not some vague blog. I have adhered to your request however. – sommmen Apr 14 '20 at 07:27