C#WPF后台加载线程,挂起退出

时间:2015-02-20 14:28:36

标签: c# wpf thread-safety

我一直试图找出启动时后台加载的问题。应用程序运行完全正常,但当它关闭时,它会永远挂起。我认为这是一个线程问题。我已将其缩小到以下代码。我一直在谷歌搜索但没有遇到任何符合我所遇到的问题的东西,有人可以详细说明这里的线程安全吗?

我认为当工人完成时(m_LoaderWindow.Close();)考虑加载屏幕是关闭的,它不会有问题。

此代码无效

            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();

此代码有效(但显然没有加载屏幕)

            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();

这是工作人员完成的代码

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

1 个答案:

答案 0 :(得分:1)

好吧,它与线程无关。在我的ViewModel中,我这样做:

public LoadingWindow m_LoaderWindow = new LoadingWindow();

然后我在主线程中将其分配为AGAIN。

虽然我无法解释为什么这会导致它在退出时挂起?