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

后端 未结 3 1985
佛祖请我去吃肉
佛祖请我去吃肉 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:57

    The async capabilities of WebClient predate .Net 4.5, so it supports the Task-based Asynchronous Pattern only partially. That includes having its own cancellation mechanism: the CancelAsync() method, which works even with the new -TaskAsync methods. To call this method when a CancellationToken is canceled, you can use its Register() method:

    cts.Token.Register(wc.CancelAsync);
    

    As an alternative, you could use the new HttpClient, as Stephen suggested, which fully supports TAP, including CancellationTokens.

提交回复
热议问题