在BackgroundWorker运行时显示表单 [英] Show a form while BackgroundWorker is running

查看:65
本文介绍了在BackgroundWorker运行时显示表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示BackgroundWorker的工作未完成时显示正在加载的表单"(带有一些文本消息的表单以及带有设置为选取框样式的progressBar的表单).完成BackgroundWorker后,必须自动关闭加载表单.尽管我确实使用了BackgroundWorker,但是主线程应该等待直到完成.我能够使用 AutoResetEvent ,但我注意到它确实阻塞了主线程,因此表单加载的progressBar也被冻结了.

I want to display a "loading form" (a form with some text message plus a progressBar with style set to marquee) while the BackgroundWorker's job isn't done. When the BackgroundWorker is done, the loading form must be closed automatically. Although I do use a BackgroundWorker, the main thread should wait until it's done. I was able to do that using a AutoResetEvent but I noticied that as it does block the main thread, the form loading's progressBar is freezed too.

我的问题是:在后台运行进程并等待其完成时,如何在不冻结该窗体的情况下显示该窗体?我希望一切都清楚.

My question is: How can I show that form without freeze it while runing a process in background and wait for it finish? I hope it's clear.

这是我当前的代码:

    BackgroundWorker bw = new BackgroundWorker();
    AutoResetEvent resetEvent = new AutoResetEvent(false);
    //a windows form with a progressBar and a label
    loadingOperation loadingForm = new loadingOperation(statusMsg);
    //that form has a progressBar that's freezed. I want to make 
    // it not freezed.
    loadingForm.Show();

    bw.DoWork += (sender, e) =>
    {
        try
        {
            if (!e.Cancel)
            {
               //do something
            }
        }
        finally
        {
            resetEvent.Set();
        }
    };

    bw.RunWorkerAsync();
    resetEvent.WaitOne();
    loadingForm.Close();
    MessageBox.Show("we are done!");

推荐答案

将您的BackgroundWorkerRunWorkerCompleted连接到将关闭表单的回调,如下所示:

Connect your BackgroundWorker's RunWorkerCompleted to a callback that will close the form like so:

private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    loadingForm.Close();  
    MessageBox.Show("we are done!");
}

您可以删除resetEvent.WaitOne();

您当然需要将loadingForm设置为字段.

在后台操作完成,被取消或引发异常时发生

Occurs when the background operation has completed, has been canceled, or has raised an exception

  • BackgroundWorker.RunWorkerCompleted
    • BackgroundWorker.RunWorkerCompleted
    • 这篇关于在BackgroundWorker运行时显示表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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