如何closures第二个UI线程

我需要能够在第二个UI线程上启动一个窗口并随意closures它。

这是我现在的代码:

/// <summary>Show or hide the simulation status window on its own thread.</summary> private void toggleSimulationStatusWindow(bool show) { if (show) { if (statusMonitorThread != null) return; statusMonitorThread = new System.Threading.Thread(delegate() { Application.Run(new AnalysisStatusWindow(ExcelApi.analyisStatusMonitor)); }); statusMonitorThread.Start(); } else { if (statusMonitorThread != null) statusMonitorThread.Abort(); statusMonitorThread = null; } } 

AnalysisStatusWindow是一个相当基本的System.Windows.Forms.Form

上面的代码正在成功创build新的UI线程,但是我的Abort线程的请求被忽略。 结果是多次切换上述函数只是导致新的窗口打开 – 所有这些都在他们自己的线程和function齐全。

有什么办法可以传递消息到这个线程closures很好吗? 如果没有,有没有办法确保Abort()真的杀死我的第二个UI线程?


我已经尝试使用new Form().Show().ShowDialog()而不是Application.Run(new Form()) ,但是它们不是更容易closures。

如果有人质疑是否需要一个单独的UI线程,则此代码存在于Excel加载项中,并且我无法控制Excel UI在给定单元格的计算过程中阻塞的事实。 出于这个原因,当长时间运行的自定义公式执行时,我需要这第二个UI线程显示进度更新。

感谢汉斯的评论。 我使用下面的代码解决了我的问题:

 /// <summary>Show or hide the simulation status window on its own thread.</summary> private void toggleSimulationStatusWindow(bool show) { if (show) { if (statusMonitorThread != null) return; statusMonitorWindow = new AnalysisStatusWindow(ExcelApi.analyisStatusMonitor); statusMonitorThread = new System.Threading.Thread(delegate() { Application.Run(statusMonitorWindow); }); statusMonitorThread.Start(); } else if (statusMonitorThread != null) { statusMonitorWindow.BeginInvoke((MethodInvoker)delegate { statusMonitorWindow.Close(); }); statusMonitorThread.Join(); statusMonitorThread = null; statusMonitorWindow = null; } }