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

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

问题描述

我有一个函数,我想每 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.

我想将锁定保持在计时器级别内,因为计时器负责何时调用我的回调,这里有一种特殊情况,当我不想调用我的回调函数时.所以我认为何时调用是计时器的责任.

I want to keep the locking inside the timer level, because the timer is responsible for when to call my callback, and here there is a particular situation when I don't want to call my callback function. So I think when to call is the responsibility of the timer.

推荐答案

我猜,由于您的问题并不完全清楚,您希望确保您的计时器在处理回调时无法重新进入回调,并且您希望在不锁定的情况下执行此操作.您可以使用 System.Timers.Timer 并确保 AutoReset 属性设置为 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天全站免登陆