c# - 将 C# System.Timer 转换为 Threading.Timer

标签 c# multithreading timer

我一直在使用 System.Timer 来运行 Windows 服务,但遇到了计时器随机不触发的问题。我昨天检查了它,当它本应每 10 分钟触发一次时,它已经超过 2 小时没有触发。我在谷歌上阅读了这个,显然这是一个已知问题,答案是切换到 Threading.Timer。我之前没有使用过它,所以一直在寻找一些见解。我目前的代码如下:

using System;
using System.Timers;
using System.ServiceProcess;

namespace Code
{
public partial class Service : ServiceBase
{
    Timer timer = new Timer();

    public Service()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer.Interval = 10000;
        timer.Enabled = true;
    }

    protected override void OnStop()
    {
        timer.Enabled = false;
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        timer.Enabled = false;
        // Run system code here
        timer.Interval = 600000;
        timer.Enabled = true;
    }
}

基本上,这通常可以正常工作。系统启动计时器并在 10 秒后触发。它停止计时器,完成工作,将计时器重置 10 分钟并启用它。在大多数情况下,这始终有效,但如前所述,随机决定停止工作,可能是由于系统资源等原因。

如果有人可以帮助我将其转换为 Threading.Timer,将不胜感激。

谢谢, 克里斯

最佳答案

这是我最好的猜测 - 没有时间测试,抱歉 :(

using System;
using System.Threading;
using System.ServiceProcess;

namespace Code
{
    public partial class Service : ServiceBase
    {
        Timer timer;
        AutoResetEvent autoEvent;
        bool stopped = true;

        public Service()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            stopped = false;
            TimerCallback tcb = new TimerCallback(OnElapsedTime);
            timer = new Timer(tcb, null, 10000, 600000);
        }

        protected override void OnStop()
        {
            stopped = true;
            timer.Dispose();
        }

        private void OnElapsedTime(Object stateInfo)
        {
            if (stopped)
                return;

            // Run system code here
        }
    }
}

关于c# - 将 C# System.Timer 转换为 Threading.Timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3297404/

相关文章:

c# - 如何按升序显示文本文件中的数据#

c# - 如果我通过ParameterizedThreadStart将对象传递给线程,我以后可以访问它吗?

c++ - 为什么这段代码catch block 不执行?

linux - 经过一定时间后释放字符驱动程序中的互斥量

javascript - 在定时器内进行 AJAX 调用并保持值

c# - 如何在 C# 中重现适合 PHP SHA512 的 SHA512 散列?

c# - 最好使用 int.Parse 或 Convert.ToInt32

c# - 如何检查当前文档类型的祖先是否是 Umbraco 中的特定类型?

iphone - 必须drawInRect : for a separate context be executed on the main thread?

python - 每 N 秒调用 2 个 python 函数