c# - 如何将 CancellationTokenSource 附加到 DownloadStringTaskAsync 方法并取消异步调用?

标签 c# .net-4.5 async-await c#-5.0 cancellationtokensource

我正在创建一个示例示例以使用 WebClient 使用异步和等待方法调用链接,现在我还想附加取消异步调用功能。但我无法获取 CancellationTokenSource token 并将 DownloadStringTaskAsync 附加到此取消 token 。以下是我的代码,任何人都可以告诉我如何完成此操作。

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.Cancel 时,不会取消 DownloadStringTaskAsync 调用。为什么取消按钮不能取消异步调用?

最佳答案

WebClient 的异步功能早于 .Net 4.5,因此它支持 the Task-based Asynchronous Pattern只是部分。这包括拥有自己的取消机制:the CancelAsync() method ,它甚至可以与新的 -TaskAsync 方法一起使用。要在取消 CancellationToken 时调用此方法,您可以使用 its Register() method :

cts.Token.Register(wc.CancelAsync);

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

关于c# - 如何将 CancellationTokenSource 附加到 DownloadStringTaskAsync 方法并取消异步调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13798539/

相关文章:

angular - 光滑的轮播在 Angular2 的 *ngFor 指令中不起作用

c# - 高效的字符串插入和搜索

c# - 如何从 Windows 8.1 商店应用程序运行 .exe 文件?

c# - 为什么可以在 WCF 服务中公开公开私有(private)方法?

c# - 使用 async/await 抛出和捕获异常的正确方法

c# - 如何运行方法而不等待长时间运行的进程

c# - 在异步方法 .net 4.5 中管理同步调用

c# - 通过 Bot Framework 发送的英雄卡中的图像未从源更新

c# - 调试 Matlab 中使用的 DLL

c# - 定义处理派生类集合的基类方法