C# 控制台应用程序计时器问题

本文关键字:问题 计时器 应用程序 控制台 | 更新日期: 2023-09-27 18:35:42

我有一个由Windows服务调用的控制台应用程序。此控制台应用程序基于某些 App.config 文件条目创建 System.Timers.Timer 的实例(我创建了一个自定义 App.config 部分,计时器实例的数量将与本节中的元素数相同)。控制台应用程序预计不会关闭 - 如果由于某种原因关闭,Windows 服务将再次调用它。

为了使控制台应用程序永远存在,我编写了一个无限循环作为控制台应用程序的最后一个语句。 而 (1 == 1) { }。

问题是,我看到控制台应用程序每 5 分钟终止一次。我不明白为什么会这样。

如果有更好的方法,请提出建议。

法典

静态空 主(字符串[] 参数) {

        Boolean _isNotRunning;
        using (Mutex _mutex = new Mutex(true, _mutexID, out _isNotRunning))
        {
            if (_isNotRunning)
            {
                new ProcessScheduler().InitializeTimers();                             
                while (1 == 1) { }                                                         
            }
            else
            {  
                return;
            }
        }

公共类进程调度程序 {

public void InitializeTimers()
    {
        XYZConfigSection.XYZAppSection section =  (XYZConfigSection.XYZAppSection)ConfigurationManager.GetSection("XYZApp");        
        if (section != null)
        {
            XYZComponentTimer XYZComponentTimer = null;
            for (int intCount = 0; intCount < section.XYZComponents.Count; intCount++)
            {
                XYZComponentTimer = new XYZComponentTimer();
                XYZComponentTimer.ComponentId = section.XYZComponents[intCount].ComponentId;
                XYZComponentTimer.Interval = int.Parse(section.XYZComponents[intCount].Interval);
                XYZComponentTimer.Elapsed += new ElapsedEventHandler(XYZComponentTimer_Elapsed);
                XYZComponentTimer.Enabled = true;                    
            }
        }
    }

}

public class XYZComponentTimer:Timer
{        
    public string ComponentId { get; set; }
}        

更新:

如代码中所述,每个实例的计时器间隔是根据相应元素的配置文件值设置的。现在,配置文件中有两个部分:一个间隔为 15 秒,另一个间隔为 10 秒。

C# 控制台应用程序计时器问题

让我猜猜:计时器间隔为 5 分钟,计时器崩溃导致进程退出。

为什么不记录任何崩溃或附加调试器?

处理 AppDomain.UnhandledException 事件并记录异常。

由于

某种奇怪的原因,Mutex 每 5 分钟被实例化一次,并将_isNotRunning设置为 true。这就是问题所在。