【C#】更新界面显示并解决this.Invoke无法访问已释放的对象

比如我在当前线程中要实时更新界面显示时间为当前时间

//声明定时器
private System.Timers.Timer timer1;
//设置定时器 (在Load里设置)
timer1 = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为1000毫秒;
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);//到达时间的时候执行事件;
timer1.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
timer1.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
private void timer1_Elapsed(object source, System.Timers.ElapsedEventArgs e)
{
    //更新界面
    this.Invoke((EventHandler)(delegate
    {
        try
        {
            TimeNow.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");                    
        }
        catch
        {
        }
    }));
}

关闭页面的时候请注意这种写法 避免出现无法访问已释放的对象

//FormClosing事件 先停下定时器
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    timer1.Stop();
}

//FormClosed事件 彻底关闭程序
private void Form1_FormClosed(object sender, FormClosingEventArgs e)
{
    System.Environment.Exit(0);
}

无法访问释放对象!!!!!

10-16

以下是form1的代码:rnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Linq;rnusing System.Text;rnusing System.Windows.Forms;rnrnnamespace _20080517S2rnrn public partial class MainForm : Formrn rn From2 fa;rn public MainForm()rn rn InitializeComponent();rn fa = new From2();rn fa.MdiParent = this;rn fa.WindowState = FormWindowState.Maximized;rn fa.button1.Click += new EventHandler(button1_Click);rn rn rn rn void button1_Click(object sender, EventArgs e)rn rn MessageBox.Show(fa.Timu);rn fa.Close();rn rn rn rn rn private void 增加题目ToolStripMenuItem_Click(object sender, EventArgs e)rn rn fa.Show();rn rn rnrnrnrn下面是form2的代码:rnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Data;rnusing System.Drawing;rnusing System.Linq;rnusing System.Text;rnusing System.Windows.Forms;rnrnnamespace _20080517S2rnrn public partial class From2: Formrn rn public From2()rn rn InitializeComponent();rn rn public string Timurn rn get return this.textBox1.Text; rn rn public string XX1rn rn get return this.textBox2.Text; rn rn public string XX2 rn get return this.textBox3.Text; rn rn public string XX3 rn get return this.textBox4.Text; rn rn public string XX4 rn get return this.textBox5.Text; rn rnrn private void button1_Click(object sender, EventArgs e)rn rn MessageBox.Show(this.Timu);rn rn rn rnrnrnrn第一次点击”增加题目“时 form2 正常SHOW出来!rnrn输入完后 点FORM2的Button1关闭rnrn然后第二次点击“增加题目”的时候就会出现 “无法访问已释放的对象” 的错误rnrn为什么会这样 rnrn环境:VS2008 论坛

System.ObjectDisposedException: 无法访问释放对象

11-18

我用C#仿照别人的写一个控件,其中用到了WebBrowser, 编译后放到HTML中,结果确出现以下错误rn有关调用实时(JIT)调试而不是此对话框的详细信息,rn请参见此消息的结尾。rnrn************** 异常文本 **************rnSystem.ObjectDisposedException: 无法访问已释放的对象。rn对象名:“WebBrowser”。rn 在 System.Windows.Forms.WebBrowser.get_AxIWebBrowser2()rn 在 System.Windows.Forms.WebBrowser.PerformNavigate2(Object& URL, Object& flags, Object& targetFrameName, Object& postData, Object& headers)rn 在 System.Windows.Forms.WebBrowser.PerformNavigateHelper(String urlString, Boolean newWindow, String targetFrameName, Byte[] postData, String headers)rn 在 System.Windows.Forms.WebBrowser.Navigate(String urlString)rn 在 CSharpActiveX.Hello.btnGo_Click(Object sender, EventArgs e) 位置 D:\VC++\CSharpActiveX\CSharpActiveX\Hello.cs:行号 110rn 在 System.Windows.Forms.Control.OnClick(EventArgs e)rn 在 System.Windows.Forms.Button.OnClick(EventArgs e)rn 在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)rn 在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)rn 在 System.Windows.Forms.Control.WndProc(Message& m)rn 在 System.Windows.Forms.ButtonBase.WndProc(Message& m)rn 在 System.Windows.Forms.Button.WndProc(Message& m)rn 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)rn 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)rn 在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)rnrnrnrn************** JIT 调试 **************rn要启用实时(JIT)调试,rn该应用程序或计算机的 .config 文件(machine.config)的 system.windows.forms 节中必须设置rnjitDebugging 值。rn编译应用程序时还必须启用rn调试。rnrn例如: rnrnrn rnrnrn启用 JIT 调试后,任何无法处理的异常rn都将被发送到在此计算机上注册的 JIT 调试器,rn而不是由此对话框处理。rnrnHTML文件代码是rnrnrn rn ActiveX测试rnrnrnrnrnrnrnrnC#的原代码:rnusing System;rnusing System.Collections.Generic;rnusing System.ComponentModel;rnusing System.Drawing;rnusing System.Data;rnusing System.Text;rnusing System.Windows.Forms;rnusing System.Runtime.CompilerServices;rnusing System.Runtime.InteropServices;rnusing System.Security; rnrnnamespace CSharpActiveXrnrn [Guid("4A44CF4E-F859-4328-AA22-3E9D7AFFF1AB")]rn public partial class Hello : UserControl, IObjectSafetyrn rn public Hello()rn rn InitializeComponent();rn rnrn #region IObjectSafety 成员rn private const string _IID_IDispatch = "00020400-0000-0000-C000-000000000046";rn private const string _IID_IDispatchEx = "a6ef9860-c720-11d0-9337-00a0c90dcaa9";rn private const string _IID_IPersistStorage = "0000010A-0000-0000-C000-000000000046";rn private const string _IID_IPersistStream = "00000109-0000-0000-C000-000000000046";rn private const string _IID_IPersistPropertyBag = "37D84F60-42CB-11CE-8135-00AA004BB851";rn private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001;rn private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002;rn private const int S_OK = 0;rn private const int E_FAIL = unchecked((int)0x80004005);rn private const int E_NOINTERFACE = unchecked((int)0x80004002);rn private bool _fSafeForScripting = true;rn private bool _fSafeForInitializing = true;rn public int GetInterfaceSafetyOptions(ref Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)rn rn int Rslt = E_FAIL;rn string strGUID = riid.ToString("B");rn pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;rn switch (strGUID)rn rn case _IID_IDispatch:rn case _IID_IDispatchEx:rn Rslt = S_OK;rn pdwEnabledOptions = 0;rn if (_fSafeForScripting == true)rn pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER;rn break;rn case _IID_IPersistStorage:rn case _IID_IPersistStream:rn case _IID_IPersistPropertyBag:rn Rslt = S_OK;rn pdwEnabledOptions = 0;rn if (_fSafeForInitializing == true)rn pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_DATA;rn break;rn default:rn Rslt = E_NOINTERFACE;rn break;rn rn return Rslt;rn rn public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)rn rn int Rslt = E_FAIL;rn string strGUID = riid.ToString("B");rn switch (strGUID)rn rn case _IID_IDispatch:rn case _IID_IDispatchEx:rn if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_CALLER) && (_fSafeForScripting == true))rn Rslt = S_OK;rn break;rn case _IID_IPersistStorage:rn case _IID_IPersistStream:rn case _IID_IPersistPropertyBag:rn if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_DATA) && (_fSafeForInitializing == true))rn Rslt = S_OK;rn break;rn default:rn Rslt = E_NOINTERFACE;rn break;rn rn return Rslt;rn rn #endregionrnrn private void button1_Click(object sender, EventArgs e)rn rn SetTime(DateTime.Now.ToLongTimeString());rn rnrn public void SetTime(string timeStr)rn rn this.label2.Text = timeStr;rn rnrn public void SayHello()rn rn SetTime("出错了");rn rnrn private void button2_Click(object sender, EventArgs e)rn rn this.label2.BackColor = Color.Red;rn rnrn private void btnGo_Click(object sender, EventArgs e)rn rn this.Browser.Navigate(txtAddr.Text);rn rnrn private void btnPreview_Click(object sender, EventArgs e)rn rn IOleCommandTarget pCmdTarg = Browser.ActiveXInstance as IOleCommandTarget;rn Guid CGID_MSHTML = GlobalConst.CGID_MSHTML;rnrn string vTemplatePath = txtTemplateAddr.Text;rn Object[] o = new object[1] vTemplatePath ;rnrn pCmdTarg.Exec(ref CGID_MSHTML,rn GlobalConst.IDM_PRINTPREVIEW,rn (uint)OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER,rn o,rn null);rn rnrn private void btnPrint_Click(object sender, EventArgs e)rn rn IOleCommandTarget pCmdTarg = Browser.ActiveXInstance as IOleCommandTarget;rn Guid CGID_MSHTML = GlobalConst.CGID_MSHTML;rnrn string vTemplatePath = txtTemplateAddr.Text;rn Object[] o = new object[1] vTemplatePath ;rnrn pCmdTarg.Exec(ref CGID_MSHTML,rn GlobalConst.IDM_PRINT,rn (uint)OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER,rn o,rn null); rn rn rnrnrn接口IObjectSafety.cs:rnusing System;rnusing System.Collections.Generic;rnusing System.Text;rnusing System.Runtime.InteropServices; rnrnnamespace CSharpActiveXrnrn [ComImport, GuidAttribute("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]rn [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] rn public interface IObjectSafetyrn rn [PreserveSig]rn int GetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] ref int pdwSupportedOptions, [MarshalAs(UnmanagedType.U4)] ref int pdwEnabledOptions); rn [PreserveSig()] rn int SetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] int dwOptionSetMask, [MarshalAs(UnmanagedType.U4)] int dwEnabledOptions); rn rnrnrn接口IOleCommandTarget.cs:rnusing System;rnusing System.Collections.Generic;rnusing System.Text;rnusing System.Runtime.InteropServices;rnusing System.Runtime.InteropServices.ComTypes;rnrnnamespace CSharpActiveXrnrn [ComImport(), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"),rn InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]rnrn public interface IOleCommandTargetrn rn [PreserveSig()]rn int QueryStatus([In, MarshalAs(UnmanagedType.Struct)] ref Guidrn pguidCmdGroup, [MarshalAs(UnmanagedType.U4)] int cCmds,rn [In, Out] IntPtr prgCmds, [In, Out] IntPtr pCmdText);rn [PreserveSig()]rn int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdExecOpt,rn [In, MarshalAs(UnmanagedType.LPArray)] object[] pvaIn,rn [In, Out, MarshalAs(UnmanagedType.LPArray)] object[] pvaOut);rnrn rnrn public enum OLECMDEXECOPTrn rn OLECMDEXECOPT_DODEFAULT,rn OLECMDEXECOPT_PROMPTUSER,rn OLECMDEXECOPT_DONTPROMPTUSER,rn OLECMDEXECOPT_SHOWHELPrn rn public static class GlobalConstrn rn public const int MSOCMDEXECOPT_DONTPROMPTUSER = 2;rn public const int IDM_PRINT = 0x1b;rn public const int IDM_PRINTPREVIEW = 0x7d3;rn public static readonly Guid CGID_MSHTML = new Guid("DE4BA900-59CA-11CF-9592-444553540000");rn public static readonly Guid IID_OleCommandTarget = new Guid("B722BCCB-4E68-101B-A2BC-00AA00404770");rn rnrnrnrn生成后rn再部署安装Setup后rnrn打开HTML页,click me和button2均无问题,rn在Document address中输入:http://www.sohu.com 然后点击Go就出现上面的错误.rn也就是说程序在rn private void btnGo_Click(object sender, EventArgs e)rn rn this.Browser.Navigate(txtAddr.Text);rn rn出错,不知怎样解决.rnrn 论坛

没有更多推荐了,返回首页