我正在创建一个示例示例以使用 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/