加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 自动处理Threading.Timer

发布时间:2020-12-15 08:30:41 所属栏目:百科 来源:网络整理
导读:我想要一些非常简单的东西 // increment counterInterlocked.Increment(ref _counter);// automatically decrement counter after 1 secTimer timer = new Timer((o) = { Interlocked.Decrement(ref _counter); (o as Timer).Dispose();},timer,1000,Timeout
我想要一些非常简单的东西
// 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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读