gpt4 book ai didi

c# - 线程已退出,Windows 窗体中的代码为 0

转载 作者:太空狗 更新时间:2023-10-30 00:42:21 24 4
gpt4 key购买 nike

我在退出 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 方法。这两个事件都是独立的并且在随机时间退出(至少我没有找到任何规则)

是什么导致了这种情况,我该如何预防?

最佳答案

如果您不保留对计时器对象的引用,它将被垃圾回收。

查看您发布的代码,您似乎没有保留引用。您需要将其设为包含类中的字段,而不是局部变量。

如果您在长时间运行的方法开始时声明它并且稍后不在该方法中引用它,则计时器也可以被垃圾收集。

您可以通过在方法 as described here 的末尾附近添加 GC.KeepAlive(timer); 来解决该特定问题.

关于c# - 线程已退出,Windows 窗体中的代码为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16054399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com