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