c# – 自动处理Threading.Timer

前端之家收集整理的这篇文章主要介绍了c# – 自动处理Threading.Timer前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要一些非常简单的东西
// increment counter
Interlocked.Increment(ref _counter);

// automatically decrement counter after 1 sec
Timer timer = new Timer((o) => {
    Interlocked.Decrement(ref _counter);
    (o as Timer).Dispose();
},timer,1000,Timeout.Infinite);

但是,此代码不可编译

Use of unassigned local variable ‘timer’

有什么简单的方法来修复它吗?它必须是Threading.Timer.

P.S.:我不确定我是否必须调用Dispose,它显然是非托管资源,它是IDisposable,仍然在msdn他们警告

As long as you are using a Timer,you must keep a reference to it. As with any managed object,a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

我实际上希望它被收集(自动处理?).那么,处置还是不处置?

解决方法

有一个模式:
Timer timer = null;
timer = new Timer...

现在你可以在lambda体中使用timer.这基本上是一种让编译器在执行相同操作时感到高兴的方法.

务必处理该计时器.定时器可能由操作系统句柄资源备份(我认为CLR实现改变了几次).我相信计时器还包含GC手柄.没有处理大部分时间都是无害的.但是谁知道你可以用大量不受干扰的计时器引发的稀有资源枯竭.

进行一些代码审查:如果您希望演员表始终有效,请不要使用因为因为文档失败是预期的情况.不是:(o作为计时器).相反:((计时器)o).

原文链接:https://www.f2er.com/csharp/243840.html

猜你在找的C#相关文章