未处理的“System.ObjectDisposedException”类型的异常出现在 system.windows.forms.dll 中

tysbaobao 2009-09-25 10:42:49
想实现一个功能,在窗口失活后5秒钟,退出应用程序。具体代码如下
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
namespace WindowsApplication4
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>

public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// 声明计时器变量。
/// </summary>
private System.ComponentModel.Container components = null;
private System.Threading.Timer timer;
private TimerCallback timerDelegate;
public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Name = "Form1";
this.Text = "Form1";
this.Activated += new System.EventHandler(this.Form1_Activated);
this.Deactivate += new System.EventHandler(this.Form1_Deactivate);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
/// <summary>
/// 在达到一定时间后调用的函数
/// </summary>
private void CheckStatus(Object state)
{
this.timer.Dispose();
this.Dispose(true);
}
//重新激活的事件处理
private void Form1_Activated(object sender, System.EventArgs e)
{
if(this.timer != null)
this.timer.Dispose();
}
//失活后的处理
private void Form1_Deactivate(object sender, System.EventArgs e)
{
if(this.timer== null)
{
this.timerDelegate = new TimerCallback(CheckStatus);
//失活间隔5秒后执行相关函数
this.timer = new System.Threading.Timer(timerDelegate, null,5000, Timeout.Infinite);
}
}
}
}
但是在执行CheckStatus进行资源清理后返回Main函数,报出未处理的“System.ObjectDisposedException”类型的异常出现在 system.windows.forms.dll 中
请教高人如何处理
...全文
1120 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qin_wei 2009-11-07
  • 打赏
  • 举报
回复
//重新激活的事件处理
private void Form1_Activated(object sender, System.EventArgs e)
{
if(this.timer != null)
this.timer.Dispose();
}
.net的对象不等于null不表示它是处于有效状态。
或者你可以这样写
if(this.timer != null)
{
this.timer.Dispose();
this.timer = null;
}
其他地方的判断和处理也一样。感觉你是刚从c++转过来的,其实托管对象很多时候不需要显式地Dispose
窗口关闭直接用this.Close();
qin_wei 2009-09-27
  • 打赏
  • 举报
回复
我被你彻底绕糊涂啦~
tysbaobao 2009-09-27
  • 打赏
  • 举报
回复
呵呵,怨我没有说清楚。
就是有一个程序主窗口Form1
设定一个计时器
在主窗口失活时开始计时
在失活达到5秒后调用程序函数
private void CheckStatus(Object state)
{
this.timer.Dispose();
this.Dispose(true);
}
但是运行时会报错
未处理的“System.ObjectDisposedException”类型的异常出现在 system.windows.forms.dll 中
不知为什么,请教高人

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧