ObjectDisposedException-在GUI线程中运行秒表 [英] ObjectDisposedException - running stopwatch in GUI thread

查看:73
本文介绍了ObjectDisposedException-在GUI线程中运行秒表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在不同线程中运行的秒表,它会更新标签中的GUI线程以显示时间的流逝.当我的程序关闭时,当我在Form GUI中调用this.Invoke(mydelegate);以使用秒表中的时间更新标签时,它将引发ObjectDisposedException.

I have a stopwatch running in a different thread, that updates the GUI thread in a label to show as time goes by. When my program closes, it throws a ObjectDisposedException when I call this.Invoke(mydelegate); in the Form GUI to update the label with the time from the stopwatch.

如何摆脱此ObjectDisposedException?

我试图在FormClosing事件中停止秒表,但它无法处理它.

I have tried to stop the stopwatch in the FormClosing Event, but it does not handle it.

代码如下:

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            stopwatch = sw;

            sw.Start();
            //System.Threading.Thread.Sleep(100);
            System.Threading.Thread t = new System.Threading.Thread(delegate()
            {
                while (true)
                {
                TimeSpan ts = sw.Elapsed;

                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);

                timeElapse = elapsedTime;

                  UpdateLabel();
                }
            });
            stopwatchThread = t;
            t.Start();

 public void UpdateLabel()
        {
            db = new doupdate(DoUpdateLabel);

            this.Invoke(db);
        }

 public void DoUpdateLabel()
        {
            toolStripStatusLabel1.Text = timeElapse;
        }

推荐答案

关闭应用程序时,秒表看起来像是被处置了,但是线程仍在运行并尝试使用它.您可以在关闭应用程序之前(在FormClosing事件中)先停止线程吗?

What it looks like is the Stopwatch is being disposed when you close your application, but the thread is still running and trying to use it. Can you stop your thread first before closing the application (in the FormClosing event)?

这篇关于ObjectDisposedException-在GUI线程中运行秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆