简体   繁体   中英

C# WPF Background Loading Thread, Hang on Exit

I have been trying to figure out a problem with a background load I do on startup. The application runs totally fine but when its closed, it hangs forever. I assumed this was a threading issue. I have narrowed it down to the following code. I have been googling around but not come across anything which fits the problem I am having, can anybody elaborate on the thread safety here?

I assumed that considering the loading screen is closed when the worker is completed ( m_LoaderWindow.Close(); ) that it wouldn't be problematic.

This code doesn't work

            m_LoaderWindow = new LoadingWindow();

            m_BackgroundWorker = new BackgroundWorker();
            OnProgressDelegate = m_BackgroundWorker.ReportProgress;
            m_BackgroundWorker.WorkerReportsProgress = true;
            m_BackgroundWorker.ProgressChanged += (object sender, ProgressChangedEventArgs arg) =>
            {
                LoaderWindow.Context.Progress = arg.ProgressPercentage;
            };

            m_BackgroundWorker.DoWork += MBackgroundWorkerOnDoWork;
            m_BackgroundWorker.RunWorkerCompleted += MBackgroundWorkerOnRunWorkerCompleted;
            m_BackgroundWorker.RunWorkerAsync();

            m_LoaderWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            m_LoaderWindow.Owner = Application.Current.MainWindow;
            m_LoaderWindow.ShowDialog();

This code works (but obviously no loading screen)

            m_BackgroundWorker = new BackgroundWorker();
            OnProgressDelegate = m_BackgroundWorker.ReportProgress;
            m_BackgroundWorker.WorkerReportsProgress = true;
            m_BackgroundWorker.ProgressChanged += (object sender, ProgressChangedEventArgs arg) =>
            {
                LoaderWindow.Context.Progress = arg.ProgressPercentage;
            };

            m_BackgroundWorker.DoWork += MBackgroundWorkerOnDoWork;
            m_BackgroundWorker.RunWorkerCompleted += MBackgroundWorkerOnRunWorkerCompleted;
            m_BackgroundWorker.RunWorkerAsync();

Here is the worker completed code

    private void MBackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
    {
        Application.Current.Dispatcher.Invoke(new Action(() =>
        {   
            m_LoaderWindow.Close();
        }));
    }

Ok it wasn't related to anything with the threading. In my ViewModel I was doing this:

public LoadingWindow m_LoaderWindow = new LoadingWindow();

And then I was allocating it AGAIN in the main thread.

Although I can't explain why this causes it to hang on exit?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM