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...";
    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...";
        worker.RunWorkerCompleted += (sender, e) =>
            this.StatusText = "Done.";

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)
    var method = new BackgroundInvokeDelegate(
    () =>
        var s = (Environment.TickCount - t).ToString();
        this.labelUIUpdating.Content = s;

Hope this article is helpful to you!

Nam Gi VU.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: