Posts Tagged ‘background’

Wait for BackgroundWorker to complete

Wait for BackgroundWorker to complete.

Advertisements

Showing a “waiting” box during a long execution

If working with WinForm/WPF application, you sometimes run into a need to show a “Please wait” box after user pressed a button which fires a long execution. The technique lies below it is as below.

The full sample codes can be downloaded here.

The original codes

Below is a sample code snippet handling the event when user press a button.

private void NoBackgrounding()
{
    this.StatusText = "Loading...";
    AVeryLongMethod();
    this.StatusText = "Loading... done.";
}

This button is in a simple form as below. The labels in red color are used to display the “waiting” box.

The problem

As in the sample handler, the execution take a long period of 10 seconds – the user will get a “not responding” state of the application. This seems to be not very friendly; a more lovely behaviour would be show a “please wait” box so as 1) to notice the user and 2) to get rid of “not responding” state.

This means we need to “move” the long execution to a background thread/worker and continue to finish the handler method. The background worker when finish will update the “waiting” box to “done”.

The codes provided with background

The the full codes to put the “long” codes in background is as below.

private void WithBackgrounding()
{
    using (var worker = new BackgroundWorker())
    {
        worker.DoWork += (sender, e) =>
        {
            this.StatusText = "Loading...";
            AVeryLongMethod();
        };
        worker.RunWorkerCompleted += (sender, e) =>
        {
            this.StatusText = "Done.";
        };
        worker.RunWorkerAsync();
    }
}

Final factor to add

In your background worker, sometimes there’re calls to update UI elements. Then, the framework needs you to invoke a method to get that works. Here’s how to make a invoke-call.

private void BackgroundRaiseErrorFixed()
{
    var t = Environment.TickCount;
    while (true)
    {
        if (Environment.TickCount - t > 2000)
        {
            break;
        }
    }
    var method = new BackgroundInvokeDelegate(
    () =>
    {
        var s = (Environment.TickCount - t).ToString();
        this.labelUIUpdating.Content = s;
    });
    this.Dispatcher.BeginInvoke(method);
}

Hope this article is helpful to you!

Nam Gi VU.

 

Fixing Error: The Calling Thread Must Be STA, Because Many UI Components Require Thi – C# | Dream.In.Code

The Calling Thread Must Be STA, Because Many UI Components Require Thi – C# | Dream.In.Code.