代码之家  ›  专栏  ›  技术社区  ›  jstuardo

关闭应用程序时如何避免ObjectDisposedException

  •  0
  • jstuardo  · 技术社区  · 7 年前

    我在整个应用程序中复制了一个问题,但我认为可以用同样的方式管理它。

    在那个类中,我有一个计时器,其tick事件是:

        private void TickTimer(object state)
        {
            Action updateText = () =>
            {
                this.Parent.SuspendLayout();
                this.Text = DateTime.Now.ToString("HH:mm:ss");
                this.Parent.ResumeLayout(false);
            };
    
            if (this.InvokeRequired)
                this.Invoke(updateText);
            else
                updateText();
        }
    

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Stop();
                _timer.Dispose();
            }
            base.Dispose(disposing);
        }
    

    问题是关闭应用程序时,此.Invoke(updateText)调用中引发异常,告知主窗体(放置控件的位置)已被释放。

    既然这是同步发生的,我该如何处理?

    通过在StackOverflow中搜索,我找到了一些建议。。。。都没用。最后一次尝试是使用“更新”标志。

        private void TickTimer(object state)
        {
            _updating = true;
    
            Action updateText = () =>
            {
                this.Parent.SuspendLayout();
                this.Text = DateTime.Now.ToString("HH:mm:ss");
                this.Parent.ResumeLayout(false);
    
                _updating = false;
            };
    
            if (this.InvokeRequired)
                this.Invoke(updateText);
            else
                updateText();
        }
    

    在处置方法中:

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Stop();
                _timer.Dispose();
    
                while (_updating) ;
            }
            base.Dispose(disposing);
        }
    

    最好的方法是什么?

    0 回复  |  直到 7 年前