【发布时间】:2012-11-27 17:22:37
【问题描述】:
我创建了一个示例示例来使用 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.");
}
当我的取消按钮调用 cts.Cancel 时,DownloadStringTaskAsync 调用不会被取消。为什么取消按钮无法取消异步调用?
【问题讨论】:
-
你没有以任何方式使用
CancellationTokeSource,WebClient怎么知道它应该在你不告诉它的情况下取消? -
感谢 svick 的回复。但是我尝试将令牌作为 DownloadStringTaskAsync 方法的参数传递,但该方法没有支持它的重载。因此,我没有得到如何将取消令牌与 DownloadStringTaskAsync 方法一起使用。你能给我推荐一些好书来阅读所有这些具有 TAP 功能的 C# 新更新吗?
标签: c# .net-4.5 async-await c#-5.0 cancellationtokensource