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

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

    Extension methods based on svick's answer:

    public static async Task DownloadStringTaskAsync(this WebClient webClient, string url, CancellationToken cancellationToken) {
        using (cancellationToken.Register(webClient.CancelAsync)) {
            return await webClient.DownloadStringTaskAsync(url);
        }
    }
    
    public static async Task DownloadStringTaskAsync(this WebClient webClient, Uri uri, CancellationToken cancellationToken) {
        using (cancellationToken.Register(webClient.CancelAsync)) {
            return await webClient.DownloadStringTaskAsync(uri);
        }
    }
    

提交回复
热议问题