我有一个在不同线程中运行的秒表,它会更新标签中的 GUI 线程以随着时间的流逝而显示。当我的程序关闭时,当我在窗体 GUI 中调用 this.Invoke(mydelegate); 以使用秒表的时间更新标签时,它会抛出 ObjectDisposedException。
如何摆脱这个ObjectDisposedException?
我试图在 FormClosing 事件中停止秒表,但它没有处理它。
代码如下:
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 事件中)?
