如何停止多个webclient DownloadStringTaskAsync

时间:2014-09-22 11:46:04

标签: c#

我有一个C#Windows窗体应用程序,其中包含多个DownloadStringTaskAsync()语句,其中显示了一个示例。我想创建一个停止按钮来取消完整的功能。我尝试添加cancelasync的代码,但它一次只停止一个语句,然后继续下一个语句。

private async void downloadfunction()
{
  string s1 = await client.DownloadStringTaskAsync(url1);
  //do something with s1

  string s2 = await client.DownloadStringTaskAsync(url2);
   //do something with s2

  string s2 = await client.DownloadStringTaskAsync(url3);
  //do something with s3
}

private void stop_Click(object sender, EventArgs e)
{
   client.CancelAsync();
}

如果我按下触发stop_Click功能的停止按钮,它会取消第一次下载,但会继续进行下一次下载。有没有办法只需按一下即可停止所有下载功能。

1 个答案:

答案 0 :(得分:3)

执行此操作的惯用方法是在方法中使用CancellationToken

(编辑:礼貌Stephen Cleary,评论)

token.ThrowIfCancellationRequested();
string s1 = await client.DownloadStringTaskAsync(url1);
token.ThrowIfCancellationRequested();
//do something with s1

token.ThrowIfCancellationRequested();
string s2 = await client.DownloadStringTaskAsync(url2);
token.ThrowIfCancellationRequested();
//do something with s2

token.ThrowIfCancellationRequested();
string s2 = await client.DownloadStringTaskAsync(url3);
token.ThrowIfCancellationRequested();
//do something with s3

token来自TaskCancellationSource的{​​{1}}媒体资源,您可以通过以下网址取消:

.Token
除了 source.Cancel(); 之外,

请注意,许多API允许您将取消令牌传递到电话中;不幸的是,显然不是这个。