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).

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么