如何向下载器添加停止按钮

时间:2016-03-24 11:58:39

标签: c#

我正在为我的应用程序工作下载器管理器,但我不知道如何使Stop按钮工作我搜索解决方案但我找不到任何可以帮助我的东西 代码是 [C#]

private void btnDownload_Click(object sender, EventArgs e)
{
  btnDownload.Enabled = false;
  btnStop.Enabled = true;
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(url.Text), path.Text ; )
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  MessageBox.Show("Download completed!");
}

private void btnstop (object sender , e)
{
  btnDownload.Enabled = true;
  btnstop.Enabled = false;
  progressbar.value = 0;   
}

2 个答案:

答案 0 :(得分:3)

正如Nitro.de所说,您应该使用WebClient.CancelAsync

  

取消挂起的异步操作。

并记住检查Stream.of(names).forEach(s -> System.out.printf("%s %d%n", s, s.length())); 是否为真

e.Cancelled

答案 1 :(得分:0)

要取消WebClient异步请求,您可以调用找到的WebClient.CancelAsync方法here。请注意,这仍然会调用下载已完成的处理程序,因此在显示消息框之前,您必须先检查e.Canceled函数中的Completed是否为 true