开发者

WaitDialog when GUI is taking a while

I have an application that can take a long time to perform some GUI updates. I can't run this in a background thread because the long processing is associated with updating GUI components which can only be done in the main thread.

Therefore, I've created a helper class which will create and disp开发者_StackOverflow中文版lay a WaitDialog form in a background thread until the GUI has finished updating.

My helper class looks like this:

public class ProgressWaitDialogHelper : IDisposable
{
    private Thread _thread = null;

    public void ShowDialog()
    {
        ThreadStart threadStart = new ThreadStart(ShowDialogAsync);
        _thread = new Thread(threadStart);
        _thread.SetApartmentState(ApartmentState.STA);
        _thread.Start();
    }

    public void Dispose()
    {
        if ((_thread != null) &&
            (_thread.IsAlive))
        {
            _thread.Abort();
        }
    }

    private void ShowDialogAsync()
    {
        ProgressWaitDialog waitDialog = new ProgressWaitDialog();
        waitDialog.ShowDialog();
    }
}

The code to call the helper class in my main GUI window looks like this:

using (ProgressWaitDialogHelper waitDialog = new ProgressWaitDialogHelper())
{
    waitDialog.ShowDialog();

    // Do long running GUI task on main thread here.
}

This seems to work fine and looks exactly like I want on the GUI. The WaitDialog form is modal and blocks access to the main GUI form until it has finished its updates. As soon as the long running GUI task is completed, it'll drop out of the Using block and thus call the Dispose method on the helper class which in turn will call Abort on the thread.

My question is, is there a more graceful way to terminate the thread or a better way of achieving the same behaviour?


I would suggest doing the actual work on the worker thread and showing your waitdialog on your GUI thread. Then you can signal your main thread when the work is done, and upon completion of the work, the thread can gracefully terminate, in a normal fashion, and you can just kill your waitdialog as you would kill any other dialog.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜