当你第二次点击时什么也没有发生
问题描述:
当我执行第二次同样的方法时,我有可怕的现象。我没有得到WPF屏幕,我不知道为什么? 参考我的代码当你第二次点击时什么也没有发生
TestWindow按钮点击方法(这是Windows应用程序项目型)和我在我的
Main()方法去除STA线程
TestClass test;
private void button1_Click(object sender, EventArgs e)
{
test =TestClass.Instance; //singleton pattern
test.ShowScreen();
}
TestClass
public void ShowScreen()
{
var thread = new Thread(() =>
{
Explorer explorer = new Explorer();
explorer.Show();
explorer.Closed += (s, args) =>
explorer.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
上面的代码工作正常,当我第一次运行。我可以查看我的资源管理器屏幕。 但问题是,当我第一次关闭屏幕,并再次调用相同的方法(test.ShowScreen();)没有表现出
注意浏览器屏幕:我注意到如果我不关闭第一窗口(实例)然后我可以打开许多资源管理器屏幕。使用相同的代码。 如果我关闭第一个窗口(实例),我无法打开资源管理器屏幕,我没有收到任何错误消息。
答
问题解决了添加在识别TestClass构造
using SW = System.Windows;
private TestClass()
{
if (SW.Application.Current == null)
{
new SW.Application
{
ShutdownMode = SW.ShutdownMode.OnExplicitShutdown
};
}
}
以下行看来的'TestClass'不恰当关闭的实例。你为什么编码相同? –
我使用的TestClass **单例模式**,真正的代码像这样'testObj = TestClass.Instance;' –
这就是它看起来的问题,读了这个[单例是一个类,它只允许一个单独的实例被创建,并且通常可以简单地访问该实例。最常见的情况是,创建实例时,单例不允许指定任何参数 - 否则,对于实例的第二个请求,但使用不同的参数可能会产生问题! (如果所有具有相同参数的请求都应该访问同一个实例,工厂模式更适合。)](http://csharpindepth.com/Articles/General/Singleton.aspx) –