非重入定时器 [英] Non-reentrant timers

查看:155
本文介绍了非重入定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想每一个的 X 的秒调用一个函数,但我希望它是线程安全的。

I have a function that I want to invoke every x seconds, but I want it to be thread-safe.

我可以设置此行为,当我创建的计时器? (我不介意,我使用的.NET定时器,我只是希望它是线程安全的)。

Can I set up this behavior when I am creating the timer? (I don't mind which .NET timer I use, I just want it to be thread-safe).

我知道我可以实现我的回调函数内的锁,但我认为这将是更优雅,如果它是在定时器水平。

I know I can implement locks inside my callback function, but I think it would be more elegant if it were in the timer level.

我的回调函数,环境不相关的UI。

My callback function, and environment are not related to a UI.


我只是不希望这是我的回调函数内部多个线程。

I just don't want there to be more than one thread inside my callback function.


我想保持计时器级别里面的锁,因为计时器负责时打电话给我的回调,而且这里还有一个特殊情况时,我不想叫我的回调函数。所以我觉得何时调用是

推荐答案

我猜定时器的责任,你的问题是不完全清楚,要确保你的计时器不能重新进入回调,而你正在处理一个回调,并且要做到这一点没有锁定。您可以通过实现这一 System.Timers.Timer 并确保自动复位属性设置为false。这将确保你必须手动触发每个间隔计时器,从而防止任何重入:

I'm guessing, as your question is not entirely clear, that you want to ensure that your timer cannot re-enter your callback whilst you are processing a callback, and you want to do this without locking. You can achieve this using a System.Timers.Timer and ensuring that the AutoReset property is set to false. This will ensure that you have to trigger the timer on each interval manually, thus preventing any reentrancy:

public class NoLockTimer : IDisposable
{
    private readonly Timer _timer;

    public NoLockTimer()
    {
        _timer = new Timer { AutoReset = false, Interval = 1000 };

        _timer.Elapsed += delegate
        {
            //Do some stuff

            _timer.Start(); // <- Manual restart.
        };

        _timer.Start();
    }

    public void Dispose()
    {
        if (_timer != null)
        {
            _timer.Dispose();
        }
    }
} 

这篇关于非重入定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆