Reputation: 1597
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();
}));
}
Upvotes: 1
Views: 289
Reputation: 1597
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?
Upvotes: 1