I'm trying to make a loading screen window. I use Show() instead of ShowDialog() because I have some code to execute after showing it. When using ShowDialog() form is fine but when using Show() form is messed up. What is causing this and what is the solution? Here is how I did it:

    bool closeLoadingWindow = false;
    void ShowLoadingWindow()
    {
        LoadingWindow loadingWindow = new LoadingWindow();
        loadingWindow.Show();
        while (!closeLoadingWindow);
        loadingWindow.Close();
        return;
    }
    public MainWindow()
    {
        Thread loadingWindowThread = new Thread(ShowLoadingWindow);
        loadingWindowThread.Start();
        InitializeComponent();
        // ...
        closeLoadingWindow = true;
    }

When using ShowDialog():

image 1

When using Show():

image 2

有帮助吗?

解决方案

The reason ShowDialog is working is because your while loop won't be executing, once the runtime hits that line of code it will stop processing until the form is dimissed.

Your code doesn't make sense, the point of using a thread here is to keep the "busy" code (your while loop) out of the main UI thread so it doesn't block. However, you are trying to create/show your form on the same thread, and a non-UI thread at that.

You don't necessarily need to use Show here, you can use ShowDialog but it is a little bit trickier in terms of dimissing the form etc. However, to solve the problem you have at the minute I would recommend you do:

LoadingWindow _loadingWindow;

void ShowLoadingWindow()
{
    if (_loadingWindow == null)
        _loadingWindow = new LoadingWindow();
    _loadingWindow.Show();
}

void HideLoadingWindow()
{
    if (_loadingWindow != null)
    {
         _loadingWindow.Close();
         _loadingWindow.Dispose();
    }
}

void LoadSomething()
{
    while (...)
    {
        // busy code goes here
    }
    // after code is finished, close the form
    MethodInvoker closeForm = delegate { HideLoadingWindow(); };
    _loadingWindow.Invoke(closeForm);
}

public MainWindow()
{
    ShowLoadingWindow();
    new Thread(LoadSomething).Start();
}
}

FYI - Depending on the nature of exactly what your trying to do in the thread it might be a better approach to use the Task Parallel Library rather than creating a dedicated thread, various benefits like continuation / cancellation support.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top