未命名的计时器线程不执行
想知道是否有人可以回答困扰我的问题。
我有一个计时器,它设置一个变量,让其他一些线程知道何时停止执行(本例中的长度是硬编码的)
Timer endProcessingThread = new Timer(x => _endOfProcessingTimeHasElapsed = true, null, 10000, 0);
我从来没有加入线程或使用计时器变量名称进行任何操作,所以我“清理”了可以说:
new Timer(x => _endOfProcessingTimeHasElapsed = true, null, 10000, 0);
这编译得很好,但线程永远不会执行。
有人知道为什么吗?
Wondering if someone can answer something that has stumped me.
I have a Timer that sets a variable to let some other threads know when to stop execution (the length is hard coded for this example)
Timer endProcessingThread = new Timer(x => _endOfProcessingTimeHasElapsed = true, null, 10000, 0);
I don't ever join on the thread or use the timers variable name for anything so I 'cleaned' it up to say:
new Timer(x => _endOfProcessingTimeHasElapsed = true, null, 10000, 0);
This compiles fine but the thread never executes.
Anyone know why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的猜测是,计时器超出了范围,并在 10 秒结束之前被 GC 了。来自 MSDN:
解决方案是通过将该引用分配给某个类或表单属性/字段,将该引用保留在 10 秒(或任何时间)内仍存在的任何代码级别。
My guess is that the Timer is going out of scope and being GCed before the 10 seconds are up. From MSDN:
The solution is to keep that reference at whatever code level will still be around in 10 seconds (or whenever) by assigning it to some class or form property/field.
首先:
Timer
是IDisposable
,因此您应该使用计时器的变量名称,至少要正确处置它。并且:由于您不保留对创建的实例的任何引用,因此它符合垃圾回收的条件。由于计时器的内部使用终结器,因此终结器会被调用,并且计时器会在有机会触发之前被删除。 (请注意,仅像第一种情况那样在命名局部变量中保留引用是不够的,编译器可能会注意到该变量根本没有被使用,并且无论如何都会对实例进行垃圾收集。
)引用并在使用完后立即调用
Dispose()
。First of all:
Timer
isIDisposable
, so that you should use the timer’s variable name, at least to dispose it properly.And: Since you do not keep any reference to the created instance, it is eligible for garbage collection. And since the internals of the Timer use a finalizer, the finalizer gets called and the timer gets deleted before it had a chance to fire. (Note that just keeping a reference in a named local variable as in your first case is not enough, the compiler might notice the variable is not used at all and garbage collect the instance anyway.)
Solution: Keep the reference and call
Dispose()
as soon as you finished using it.匿名计时器可能在触发之前被垃圾收集器清理。
请参阅这个SO问题。
The anonymous Timer is possibly cleaned up by the Garbage collector before it triggers.
See this SO question.
可能是因为您从未持有对您创建的对象的引用,所以它要么立即被优化(无左值),要么只是被 GC 处理并且从不执行。
FWIW 该类没有实现 IDisposable 吗?如果是这样,您应该使用
using
语句或调用 dispose。It could be that since you never hold a reference to the object you create, it either gets optimized away immediately (no lvalue) or it simply get GC'd and never executes.
FWIW doesn't that class implement IDisposable? If so, you should be using a
using
statement or calling dispose.