我创建了一个示例示例以使用 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 调用不会被取消。为什么取消按钮无法取消异步调用?