How to attach CancellationTokenSource to DownloadStringTaskAsync method and cancel the async call?

后端 未结 3 1992
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 13:10

I an creating a sample example to call link using WebClient using async and await method now I want to attach cancel async call functionality also. But I am not able to get Can

3条回答
  •  庸人自扰
    2021-02-05 13:53

    WebClient doesn't support cancellation. I recommend you use a newer type such as HttpClient:

    ...
    cts = new CancellationTokenSource();
    string result;
    using (var client = new HttpClient())
    using (var response = await client.GetAsync("http://gyorgybalassy.wordpress.com", cts.Token))
    {
      result = await response.Content.ReadAsStringAsync();
    }
    
    if (result.Length < 100000)
    ...
    

    The GetAsync method by default will not complete until it reads the entire response, so the await response.Content.ReadAsStringAsync line will actually complete synchronously.

提交回复
热议问题