我在 Windows 窗体中退出线程时遇到问题。
我有经典的 Windows 窗体,它正在运行。我需要每隔一段时间做一些事情,所以我补充说:
TimerCallback timerDelegate = new TimerCallback(this.TryDoSomething);
int period = 10 * 1000; // to miliseconds
System.Threading.Timer stateTimer = new System.Threading.Timer(timerDelegate, null, period, period);
方法 DoSomething 由几个线程(主线程和这个计时器)调用,所以我这样介绍:
private void TryDoSomething(object o)
{
lock (tryDoSomethingMutex)
{
if (this.dataGridView1.InvokeRequired)
{
RefreshCallback d = new RefreshCallback(DoSomething);
this.Invoke(d, new object[] { o });
}
else
{
this.DoSomething(o);
}
}
}
一切正常,直到我的计时器线程刚刚退出并显示消息:
The thread 0x2798 has exited with code 0 (0x0).
我的 FileSystemWatcher 也发生了同样的事情,它也调用了 DoSomething 方法。这两个事件都是独立的,并且在随机时间退出(至少我没有找到任何规则)
是什么导致了这种情况,我该如何预防?