什么是这个set_Visible异常的起源在关闭winforms应用程序
本文关键字:起源 应用程序 winforms 异常 set Visible 什么 | 更新日期: 2023-09-27 18:10:13
我已经包装了应用程序。在try/catch
中运行方法[STAThread]
private static void Main(string[] args)
{
try {
MyClient client = new MyClient();
client.Run(args);
}
catch (Exception ex) { log.Error("Failed to start client",ex); }
}
Where MyClient is just:
class MyClient : WindowsFormsApplicationBase
在每次关机时我都会得到这个异常
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'MainView'.
at System.Windows.Forms.Control.CreateHandle()
at System.Windows.Forms.Form.CreateHandle()
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
at System.Windows.Forms.Control.set_Visible(Boolean value)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at MyProgram.Main(String[] args) in C:'svn'trunk'MyProgram'client'MyProgram'Program.cs:line 54
如果我在catch块中的调试器中设置了一个断点,那么除了client.Run(..)
之外,我的调用堆栈都是空的。
就我所能理解的堆栈跟踪问题是在某个地方,一些代码正在做MainView.Visible = ....
,但我可以在我的代码中找到任何类似的东西。
如何找出异常的来源?
MainView是这样在MyClient
中创建的:
protected override void OnCreateMainForm()
{
string[] args = Environment.GetCommandLineArgs();
try {
MainView mainView = new MainView(args);
this.MainForm = mainView;
Application.EnableVisualStyles();
Application.Run(mainView);
}catch(Exception ex){ log.Warn("Exception in OnCreateMainForm",ex); }
}
像这样结束:
public void OnKilled()
{
log.Debug("OnKilled. Exiting");
Application.Exit();
}
MainView
定义如下:
public partial class MainView : Form
{
private void InitializeComponent()
{
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainView_FormClosing);
}
private void MainView_FormClosing(object sender, FormClosingEventArgs e)
{
log.DebugFormat("'MainView_FormClosing': {0}",e.CloseReason);
if (e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.ApplicationExitCall)
{
e.Cancel = false;
Application.Exit();
}
}
你能把你用来创建主窗口的代码和你用来关闭主窗口的代码贴出来吗?
没有看到更多的代码,我猜在你的代码的某个地方,你正在调用Dispose
的窗口,而不是使用Close
。但这只是猜测。
WindowsFormsApplicationBase
? 啊哈!
事实证明,Application.Run
在OnCreateMainForm是一个大的禁忌。当OnCreateMainForm
返回时,WindowsFormsApplicationBase
接管ApplicationRun,因此在我的情况下,当MainForm已经被处置时,我只从OnCreateMainForm
返回,因此异常:(
protected override void OnCreateMainForm()
{
string[] args = Environment.GetCommandLineArgs();
try {
MainView mainView = new MainView(args);
this.MainForm = mainView;
Application.EnableVisualStyles();
}...
}