如何停止多个Web客户端DownloadStringTaskAsync

本文关键字:客户端 DownloadStringTaskAsync Web 何停止 | 更新日期: 2023-09-27 18:23:49

我有一个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功能的停止按钮,它将取消第一次下载,但随后继续下一次。有没有办法只需点击一下就可以停止所有下载功能。

如何停止多个Web客户端DownloadStringTaskAsync

实现这一点的惯用方法是在方法中使用CancellationToken

(编辑:斯蒂芬·克利里提供,评论)

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.Token属性,然后可以通过:取消该属性

source.Cancel();

除了client.CancelAsync()

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