如何将 CancellationTokenSource 附加到 DownloadStringTaskAsync 方法并取消异步调用? [英] How to attach CancellationTokenSource to DownloadStringTaskAsync method and cancel the async call?
问题描述
我创建了一个示例示例来使用 WebClient 使用 async 和 await 方法调用链接,现在我还想附加取消异步调用功能.但我无法获得 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.Cancel 时,不会取消 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 CancellationToken
s.
这篇关于如何将 CancellationTokenSource 附加到 DownloadStringTaskAsync 方法并取消异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!