如何将CancellationTokenSource附加到DownloadStringTaskAsync方法并取消异步调用? [英] How to attach CancellationTokenSource to DownloadStringTaskAsync method and cancel the async call?

查看:126
本文介绍了如何将CancellationTokenSource附加到DownloadStringTaskAsync方法并取消异步调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个示例示例,以使用异步和等待方法使用WebClient调用链接,现在我也想附加取消异步调用功能。但是我无法获取CancellationTokenSource令牌并将DownloadStringTaskAsync附加到此取消令牌。

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 CancellationTokenSource token and attach DownloadStringTaskAsync to this cancellation token. Following Is my code can anyone tell me how to accomplish this.

private async void DoWork()
        {
            this.Cursor = Cursors.WaitCursor;
            Write("DoWork started.");
            cts = new CancellationTokenSource();
            WebClient wc = new WebClient();
            string result = await wc.DownloadStringTaskAsync(new Uri("http://gyorgybalassy.wordpress.com"));

            if (result.Length < 100000)
            {
                Write("The result is too small, download started from second URL.");
                result = await wc.DownloadStringTaskAsync(new Uri("https://www.facebook.com/balassy"));
            }
            Write("Download completed. Downloaded bytes: " + result.Length.ToString());
            Write("DoWork ended.");
            this.Cursor = Cursors.Default;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Write("Cancellation started.");
            this.cts.Cancel();
            Write("Cancellation ended.");
        }

当我的取消按钮调用cts时,不会取消取消DownloadStringTaskAsync调用。为什么取消按钮无法取消异步调用?

When my Cancel button calls cts.Cancel the DownloadStringTaskAsync call is not canceled. Why cancel button is not able to cancel the Async calls?

推荐答案

WebClient 的异步功能早于.Net 4.5,因此它仅支持基于任务的异步模式部分地。这包括拥有自己的取消机制: CancelAsync() 方法,甚至可以使用新的 -TaskAsync 方法。若要取消 CancellationToken 时调用此方法,可以使用 Register()方法

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);

作为替代,您可以使用新的 HttpClient ,正如Stephen所建议的那样,它完全支持TAP,包括 CancellationToken s。

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

这篇关于如何将CancellationTokenSource附加到DownloadStringTaskAsync方法并取消异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆