Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

c# - Show a form while BackgroundWorker is running

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.

Here's my current code:

    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!");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!");
}

You can delete the resetEvent.WaitOne();

You'll need to make loadingForm a field of course.

Tell me more

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...