关闭表单时,如何防止倒数计时器引发异常

时间:2019-08-23 16:30:59

标签: c# winforms timer

我的应用程序有一个主窗口和一个处理窗口。处理窗口包含一个倒数计时器,向用户提供有关何时进行处理的反馈。倒数秒是一秒,因此通常会在关闭处理窗口时触发。然后引发异常“无法访问已处置的对象”。我捕获了此异常,但我希望它没有发生。另外,有时我看到应用程序冻结,并且处理窗口没有关闭。我怀疑这是一种相关行为,无法通过捕获异常来阻止。

我的代码:

    private System.Timers.Timer _timer;

    // in form constructor
    _timer = new System.Timers.Timer { Interval = 1000 };
    _timer.Elapsed += OnTimeEvent;


    // when processing starts this method resets timer
    private void OnFilesChecked()
    {
        if (IsDisposed)
            return;

        try
        {
            if (_timer.Enabled)
            {
                _timer.Stop();
            }

            Invoke(new Action(() => { toolStripLabelTimer.Text = TrackProcessor.Watcher.PauseTime.ToString(); }));
            _timer.Start();
        }
        catch (Exception ex)
        {
            LaunchWindow.RtbError.WriteLine("Exception Handled: {0}", ex);
            //throw;
        }
    }

    private void OnTimeEvent(object sender, ElapsedEventArgs e)
    {
        if (IsDisposed)
            return;
        try
        {
            Invoke(new Action(() =>
            {
                var time = Int32.Parse(toolStripLabelTimer.Text);
                time -= 1;
                toolStripLabelTimer.Text = time.ToString();
                if (time == 0 && _timer != null && _timer.Enabled)
                    _timer.Stop();
            }));
        }
        catch (Exception ex)
        {
            LaunchWindow.RtbError.WriteLine("Exception Handled: {0}", ex);
            //throw;
        }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        base.OnFormClosing(e);

        _timer.Stop();
        _timer.Dispose();

        // send event back to launchwindow so the run button can be enabled.
        DisposeEvent?.Invoke();
    }

1 个答案:

答案 0 :(得分:-1)

在OnClosingForm中,您需要删除_timer.Dispose();

之后,在处理表单构造函数中调用

_timer.Start();  

,最后在析构函数集中_timer.Dispose(); 现在,您可以从主窗体中的对象调用析构函数。