下载后 WebClient 冻结 [英] WebClient freeze after download

查看:59
本文介绍了下载后 WebClient 冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临另一个问题,我的应用程序从网络下载一个文件,提取它,删除它等等,它在第一次运行时运行良好,然后在下载下一个文件时它只是冻结了下载并永远挂在那里......这可能是试图打开一个已经打开的连接,但我不知道如何关闭它,这是我第一次使用 C# 联网,我是自学的.

I'm facing another problem, my application downloads a file from a web, extracts it, deletes it and so on, it runs fine for the first run, then when it comes to downloading the next file it simply freezes the download and hangs there forever.. It's probably something with trying to open an already open connection, but I have no idea how to close it, this is my first time networking with C# and I'm self teaching.

我的代码:

  public void start() {
        if (File.Exists("Data/version.txt")) { File.Delete("Data/version.txt"); }
        label1.Text = "Getting update information...";
        WebClient webClient = new WebClient();
        webClient.DownloadFileAsync(new Uri("http://127.0.0.1/update/version.txt"), @"Data/version.txt");
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(versionCompleted);
    }

    private void versioncheck() {
        if (File.Exists("Main.exe"))
        {       
            label1.Text = "Contacting update server...";
                var versionInfo = FileVersionInfo.GetVersionInfo("Main.exe");
                string version = versionInfo.ProductVersion;
                string[] nversion = version.Split('.');
                string updateversion = nversion[3];

                int version = Int32.Parse(updateversion);
                ///////////////////////////////////////////////////////////
                StreamReader sr = new StreamReader("Data/version.txt");
                ///////////////////////////////////////////////////////////
                string readline = sr.ReadLine();
                sr.Dispose();
                int serverversion = Int32.Parse(readline);

                if (serverversion > version) {
                    string filenumber = (version+1).ToString();
                    downloadfile(filenumber); 
                }
                else if(serverversion == version){
                    label1.Text = "Game is up to date!";
                    startButton.Enabled = true;
                }

        }
        else { MessageBox.Show("Unexpected Error!", "Error!"); }
    }

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

    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        label1.Text = "Extracting Files...";
        var versionInfo = FileVersionInfo.GetVersionInfo("Main.exe");
        string version = versionInfo.ProductVersion;
        string[] nversion = version.Split('.');
        string updateversion = nversion[3];
        int version = Int32.Parse(updateversion); string nversion = (version + 1).ToString();

        Process proc = Process.Start("update"+nversion+".exe"); // extract in the silent mode
        proc.WaitForExit();
        File.Delete("update" + nversion + ".exe");
        label1.Text = "Checking for more updates...";
        versioncheck();
    }

    private void versionCompleted(object sender, AsyncCompletedEventArgs e) {
        versioncheck();
    }

    private void downloadfile(string filenumber)
    {
        try
        {
            //MessageBox.Show("Download working");
            System.Net.WebClient webClient = new System.Net.WebClient();
            webClient.OpenRead("http://127.0.0.1/Update/update" + filenumber + ".exe");
            Int64 bytes_total = Convert.ToInt64(webClient.ResponseHeaders["Content-Length"]);
            string updatelength = Convert.ToString((bytes_total / 1024).ToString());
            label2.Text = "File size:" + updatelength + "KB";
            ////////////////////////////////////////////////////
            label1.Text = "Downloading Update...";
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
            webClient.DownloadFileAsync(new Uri("http://127.0.0.1/Update/update" + filenumber + ".exe"), @"update"+filenumber+".exe");
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            webClient.Dispose();

        }
        catch (WebException )
        {
            MessageBox.Show("Connection error!", "Error!");
            Application.Exit();
        }
        catch (IOException)
        {
            MessageBox.Show("Unknown Error!", "Error!");
            Application.Exit() ;
        }       
    }

推荐答案

如果你使用 async 操作,你需要使用 async 和 await 关键字.

If u use async operation u gonne need to use the async and await keywords.

您需要在完成下载或失败时处理或关闭您的网络客户端.

U need to dispose or close your webclient when it is done downloading or failing.

正如 b1tsh1ft 所说,最好的方法是使用 using 语句.

As b1tsh1ft stated best thing is to use the using statement.

string version = versionInfo.ProductVersion;
string[] nversion = version.Split('.');

int version = Int32.Parse(updateversion); 
string nversion = (version + 1).ToString();

难道你的 VS 没有在你的编辑器中给出一个有冲突的错误吗?

Isn't your VS not giving a conflicting error in your editor about this ?

这篇关于下载后 WebClient 冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆