C# 如何关闭第二个UI线程
我需要能够在第二个UI线程上启动一个窗口,然后再随意关闭它 这是我当前的代码:C# 如何关闭第二个UI线程,c#,multithreading,excel,C#,Multithreading,Excel,我需要能够在第二个UI线程上启动一个窗口,然后再随意关闭它 这是我当前的代码: /// <summary>Show or hide the simulation status window on its own thread.</summary> private void toggleSimulationStatusWindow(bool show) { if (show) { if (statusMonitorThread != null
/// <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;
}
}
///在自己的线程上显示或隐藏模拟状态窗口。
专用无效切换模拟状态窗口(布尔显示)
{
如果(显示)
{
if(statusMonitorThread!=null)返回;
statusMonitorThread=new System.Threading.Thread(委托()
{
运行(新的AnalysisStatusWindow(ExcelApi.AnalysisStatusMonitor));
});
statusMonitorThread.Start();
}
其他的
{
if(statusMonitorThread!=null)
statusMonitorThread.Abort();
statusMonitorThread=null;
}
}
AnalysisStatusWindow
是一个相当基本的System.Windows.Forms.Form
上面的代码正在成功创建新的UI线程,但是我对中止
线程的请求被忽略。其结果是,多次切换上述函数只会打开新窗口——所有窗口都在各自的线程上,功能齐全
有没有什么方法我可以传递一个消息给这个线程,让它很好地关闭?如果做不到这一点,有没有办法确保Abort()
真的杀死了我的第二个UI线程
我尝试过使用
newform().Show()
和.ShowDialog()
而不是Application.Run(newform())
,但它们并不容易关闭
如果有人质疑是否需要单独的UI线程,则此代码存在于Excel加载项中,我无法控制这样一个事实,即Excel UI在对给定单元格进行计算时会阻塞。因此,当执行长时间运行的自定义公式时,我需要第二个UI线程显示进度更新。感谢Hans的评论。我使用以下代码解决了我的问题:
/// <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;
}
}
///在自己的线程上显示或隐藏模拟状态窗口。
专用无效切换模拟状态窗口(布尔显示)
{
如果(显示)
{
if(statusMonitorThread!=null)返回;
statusMonitorWindow=新的AnalysisStatusWindow(ExcelApi.AnalysisStatusMonitor);
statusMonitorThread=new System.Threading.Thread(委托()
{
Application.Run(状态监视器窗口);
});
statusMonitorThread.Start();
}
else if(statusMonitorThread!=null)
{
statusMonitorWindow.BeginInvoke((MethodInvoker)委托{statusMonitorWindow.Close();});
statusMonitorThread.Join();
statusMonitorThread=null;
statusMonitorWindow=null;
}
}
您需要公开该表单实例,以便调用其BeginInvoke()方法。对仅调用this.Close()的form类调用公共方法;谢谢你,伙计,这正是我需要的想法。你的BeginInvoke
可以简化为statusMonitorWindow.BeginInvoke((MethodInvoker)statusMonitorWindow.Close)代码>asClose()
满足MethodInvoker
签名。