当我尝试取消DownloadFileTaskAsync时,我的WPF应用程序崩溃并关闭

时间:2015-08-27 08:02:54

标签: c# wpf download webclient

我正在创建一个WPF应用程序,我使用WebClient从Web服务器下载文件。当我下载文件时,我的WPF应用程序崩溃并在我尝试取消下载时关闭。并非总是会发生这种情况。有时取消成功,但最重要的是我不知道它的行为是这样的。谢谢

  public async Task DownloadProtocol(int torrentId, string address, string location)
    {
        Uri Uri = new Uri(address);
        try
        {
            using (client = new WebClient())
            {

                sw.Start();
                client.DownloadProgressChanged += (o, e) =>
                {
                    var thisGame = MainWindow._items.Find(item => item.Id == torrentId);
                    PercentageDone = (e.BytesReceived / TotalSize) * 100;

                    thisGame.Progress = (int)SizeReceived + (int)PercentageDone;

                    Console.Write("\r {0} ", PercentageDone);

                };

                client.DownloadFileCompleted += (o, e) =>
                {
                    if (e.Cancelled == true)
                    {
                        Console.WriteLine("Download has been canceled.");
                    }
                    else
                    {

                        Console.WriteLine("Download completed!");
                        SizeReceived += PercentageDone;
                    }

                    client.Dispose();
                };

                await client.DownloadFileTaskAsync(Uri, location);
            }
        }
        catch(WebException ex)
        {
            Log.Logger("Download error ", ex);
        }

    }  

取消功能:

    public void Cancel()
    {
        if(client != null)
        {
            client.CancelAsync();
        }
    }

0 个答案:

没有答案