我创建一个示例示例,使用WebClient使用async和await方法调用链接现在我还要附加取消异步调用功能.但是我无法获取CancellationTokenSource令牌,并将DownloadStringTaskAsync附加到此取消令牌.以下是我的代码可以告诉我如何完成这个.
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."); }
当我的Cancel按钮调用cts.Cancel时,DownloadStringTaskAsync调用不会被取消.为什么取消按钮不能取消Async电话?
解决方法
WebClient的异步功能早于.Net 4.5,所以它仅部分支持
the Task-based Asynchronous Pattern.这包括自己的取消机制:
the
CancelAsync()
method,甚至可以使用新的-TaskAsync方法.要取消取消指令时调用此方法,可以使用
its Register()
method:
cts.Token.Register(wc.CancelAsync);
作为替代方案,您可以像Stephen所建议的那样使用新的HttpClient,它完全支持TAP,包括CancellationTokens.