Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何取消下载异步?_C#_Asynchronous_Download - Fatal编程技术网

C# 如何取消下载异步?

C# 如何取消下载异步?,c#,asynchronous,download,C#,Asynchronous,Download,我有个问题。如何取消下载 client.CancelAsync(); 不适用于我,因为如果我取消下载并开始新的下载,代码仍会尝试访问旧的下载文件。您必须知道,在我的代码中,当下载完成时,它应该解压缩已下载的文件。Example.zip,如下所示:) 所以,当我取消下载并开始一个新的下载时,你知道我的脚本试图解压我的旧Example.zip,但它应该会触发这个 对于解压缩,我使用的是icogal.Zip.dll() 如何让它工作 更新: 这是我的下载表 private void b

我有个问题。如何取消下载

 client.CancelAsync();
不适用于我,因为如果我取消下载并开始新的下载,代码仍会尝试访问旧的下载文件。您必须知道,在我的代码中,当下载完成时,它应该解压缩已下载的文件。Example.zip,如下所示:) 所以,当我取消下载并开始一个新的下载时,你知道我的脚本试图解压我的旧Example.zip,但它应该会触发这个

对于解压缩,我使用的是icogal.Zip.dll()

如何让它工作


更新:

这是我的下载表

     private void button3_Click_1(object sender, EventArgs e)
    {

        DialogResult dialogResult = MessageBox.Show("This will cancel your current download ! Continue ?", "Warning !", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {

            cancelDownload = true;
            URageMainWindow.isDownloading = false;
            this.Close();

        }
        else if (dialogResult == DialogResult.No)
        {

        } 
    }
这是我的主要形式,当你开始下载东西时会发生这种情况

 private void checkInstall(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

            string input = storeBrowser.Url.ToString();

            // Test these endings
            string[] arr = new string[]
           {"_install.html"};

            // Loop through and test each string
            foreach (string s in arr)
            {
                if (input.EndsWith(s) && isDownloading == false)
                {


                   // MessageBox.Show("U.Rage is downloading your game");
                    Assembly asm = Assembly.GetCallingAssembly();
                    installID = storeBrowser.Document.GetElementById("installid").GetAttribute("value");
                   // MessageBox.Show("Name: " + installname + " ID " + installID);
                    installname = storeBrowser.Document.GetElementById("name").GetAttribute("value");
                    installurl = storeBrowser.Document.GetElementById("link").GetAttribute("value");

                    isDownloading = true;
                    string install_ID = installID;
                    string Install_Name = installname;

                    // MessageBox.Show("New Update available ! " + " - Latest version: " + updateversion + "  - Your version: " + gameVersion);
                    string url = installurl;
                    WebClient client = new WebClient();
                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_InstallProgressChanged);
                    client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_InstallFileCompleted);
                    client.DownloadFileAsync(new Uri(url), @"C:\U.Rage\Downloads\" + installID + "Install.zip");
                    if (Downloader.cancelDownload == true)
                    {
                        //MessageBox.Show("Downloader has been cancelled");
                        client.CancelAsync();
                        Downloader.cancelDownload = false;
                    }
                    notifyIcon1.Visible = true;
                    notifyIcon1.ShowBalloonTip(2, "Downloading !", "U.Rage is downloading " + installname, ToolTipIcon.Info);
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:/U.Rage/Sounds/notify.wav");
                    player.Play();

                    storeBrowser.GoBack();
                    igm = new Downloader();
                    igm.labelDWGame.Text = installname;
                    // this.Hide();
                    igm.Show();
                    return;
                }

                  if (input.EndsWith(s) && isDownloading == true)
                {
                  System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:/U.Rage/Sounds/notify.wav");
                  player.Play();
                  MessageBox.Show("Please wait until your download has been finished", "Warning");
                  storeBrowser.GoBack();
                }
            }
        }
下载完成后会发生这种情况

     void client_InstallFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        if(Downloader.cancelDownload == false)
        {
            using (ZipFile zip = ZipFile.Read(@"C:\U.Rage\Downloads\" + installID + "Install.zip"))
            {
                //zip.Password = "iliketrains123";
                zip.ExtractAll("C:/U.Rage/Games/", ExtractExistingFileAction.OverwriteSilently);
            }
            System.IO.File.Delete(@"C:/U.Rage/Downloads/" + installID + "Install.zip");
            notifyIcon1.Visible = true;
            notifyIcon1.ShowBalloonTip(2, "Download Completed !", "Installing was succesful !", ToolTipIcon.Info);
            System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:/U.Rage/Sounds/notify.wav");
            player.Play();
            this.Show();
            igm.Close();
            isDownloading = false;
            listView.Items.Clear();
            var files = Directory.GetFiles(@"C:\U.Rage\Games\", "*.ugi").Select(f => new ListViewItem(f)).ToArray();
            foreach (ListViewItem f in files)
            {
                this.LoadDataFromXml(f);
            }

      }
    }

调用
CancelAsync
时,传递给已完成回调的
AsyncCompletedEventArgs
对象将
Cancelled
属性设置为true。所以你可以写:

void client_InstallFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    if(e.Cancelled)
    {
        // delete the partially-downloaded file
        return;
    }
    // unzip and do whatever...
    using (ZipFile zip = ZipFile.Read(@"C:\U.Rage\Downloads\" + installID + "Install.zip"))

有关更多信息,请参阅

选择的答案对我来说不合适。以下是我所做的:

当他们单击“取消”按钮时,我调用

Client.CancelAsync();
然后在Web.Client下载文件中完成:

Client.DownloadFileCompleted += (s, e) =>
{
      if (e.Cancelled)
      {
          //cleanup delete partial file
          Client.Dispose();                    
          return;
      }
 }
然后,当您尝试重新下载时,只需实例化一个新客户端:

Client = WebClient();

这样就不会保留旧的异步参数。

以下是支持取消的异步数据下载方法:

private static async Task<byte[]> downloadDataAsync(Uri uri, CancellationToken cancellationToken)
{
    if (String.IsNullOrWhiteSpace(uri.ToString()))
        throw new ArgumentNullException(nameof(uri), "Uri can not be null or empty.");

    if (!Uri.IsWellFormedUriString(uri.ToString(), UriKind.Absolute))
        return null;

    byte[] dataArr = null;
    try
    {
        using (var webClient = new WebClient())
        using (var registration = cancellationToken.Register(() => webClient.CancelAsync()))
        {
            dataArr = await webClient.DownloadDataTaskAsync(uri);
        }
    }
    catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
    {
        // ignore this exception
    }

    return dataArr;
}
私有静态异步任务下载DataAsync(Uri Uri,CancellationToken CancellationToken)
{
if(String.IsNullOrWhiteSpace(uri.ToString()))
抛出新ArgumentNullException(nameof(uri),“uri不能为null或空。”);
if(!Uri.iswellFormedUrString(Uri.ToString(),UriKind.Absolute))
返回null;
字节[]dataArr=null;
尝试
{
使用(var webClient=new webClient())
使用(var registration=cancellationToken.Register(()=>webClient.CancelAsync())
{
dataArr=等待webClient.DownloadDataTaskAsync(uri);
}
}
捕获(WebException ex)时间(ex.Status==WebExceptionStatus.RequestCancelled)
{
//忽略此异常
}
返回数据arr;
}

很好。取消此操作有效,但他仍在下载旧的:P如何启动流或用新的下载链接替换它?他取消旧的下载并创建新的dl文件,但仍在旧文件中添加字节感谢我修复了它我忘了将我的WebClient公开:)Downvoter,通常是提供downvote的原因。