由于form_load代码而停止应用程序不显示

时间:2013-10-01 23:21:40

标签: c#

在form_load代码完成之前,如何阻止我的应用程序不显示?

public partial class updater : Form
{
    public updater()
    {           
        InitializeComponent();
        timer1.Interval = (10000) * (1);
        progressBar1.Value = 0;
        progressBar1.Maximum = 100;
        progressBar1.Update();
        timer1.Start();
    }

    private void updater_Load(object sender, EventArgs e)
    {          
        WebClient webClient = new WebClient();
        webClient.DownloadProgressChanged += webClient_DownloadProgressChanged;

        webClient.DownloadFile("http://download827.mediafire.com/jl9c098fnedg/ncqun56uddq0y1d/Stephen+Swartz+-+Survivor+%28Feat+Chloe+Angelides%29.wav", Application.StartupPath + "\\Stephen Swartz - Survivor (Feat Chloe Angelides).wav");
        // System.Diagnostics.Process.Start("\\Test.exe");
        this.Close();   
    }
    void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
        progressBar1.Update();
    }
}

2 个答案:

答案 0 :(得分:3)

如果您使用DownloadFileAsync,它将不会阻止UI线程并允许Form加载并在Progressbar中显示进度,那么您可以使用DownloadFileCompleted要关闭Form

的事件

示例:

    public Form1()
    {
        InitializeComponent();
        progressBar1.Value = 0;
        progressBar1.Maximum = 100;
        progressBar1.Update();
    }

    private void updater_Load(object sender, EventArgs e)
    {
        WebClient webClient = new WebClient();
        webClient.DownloadProgressChanged += webClient_DownloadProgressChanged;
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
        webClient.DownloadFileAsync(new Uri("http://download827.mediafire.com/jl9c098fnedg/ncqun56uddq0y1d/Stephen+Swartz+-+Survivor+%28Feat+Chloe+Angelides%29.wav"), Application.StartupPath + "\\Stephen Swartz - Survivor (Feat Chloe Angelides).wav");
    }

    private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        Close();
    }

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

答案 1 :(得分:1)

一种方法是从加载Shown Event移动代码。因此,代码将在显示表单后开始运行。

另一个是创建thread,您将在其中下载文件。 为此,您可以使用BackgroundWorker

private void updater_Load(object sender, EventArgs e)
{     
    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += (s, eArgs) =>
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFile("someUrl", "somePath");
        };
    worker.RunWorkerAsync();
}

同样存在webClient.DownloadFileAsync方法,在这种情况下更适合。你可以在sa_ddam213回答中找到描述。