C# Windows 服务 - 计时器在调试中不工作

C# Windows Service - Timer is not working in debugging

我已经开始使用 c# 语言构建 windows 服务。我想在其中实现计时器功能。但出于某种原因,DoIt 计时器事件处理程序在调试期间没有被触发,我也没有收到任何异常。我正在尝试使用 Debug->Start new instance 来调试 windows 服务。

行TraceLog.WriteTrace("Router Service Started");确实被击中并被处决。

   public partial class EntryPoint : ServiceBase
    {
        private const int TIMER_INTERVAL = 10000;
        private System.Timers.Timer mvTimer = new System.Timers.Timer();

        [MTAThread()]
        [System.Diagnostics.DebuggerNonUserCode()]
        public static void Main()
        {
            #if DEBUG
                        EntryPoint service = new EntryPoint();
                        service.Start();
            #else
                        ServiceBase[] ServicesToRun;
                        ServicesToRun = new ServiceBase[] 
                        { 
                            new EntryPoint() 
                        };
                        ServiceBase.Run(ServicesToRun);
            #endif
        }
        public EntryPoint()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            InitializeComponent();
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            if (ex != null)
            {
                Console.WriteLine(ex);
            }
        }


        public void Start()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            TraceLog.SetTrace(ConfigurationManager.AppSettings["RouterTraceLog"]);
            TraceLog.WriteTrace("Router Service Started");

            mvTimer = new Timer();
            mvTimer.Elapsed += new ElapsedEventHandler(DoIt);
            try
            {
                mvTimer.Interval = TIMER_INTERVAL;
                mvTimer.Enabled = true;                
            }
            catch (Exception ex)
            {
                mvTimer.Interval = TIMER_INTERVAL;
                TraceLog.WriteTrace(ex.Message);
            }
        }

        private void DoIt(object sender, ElapsedEventArgs e)
        {
            TraceLog.WriteTrace("Inside DoIt :: " + DateTime.UtcNow.ToString());
        }

        protected override void OnStop()
        {
            mvTimer.Enabled = false;
            TraceLog.WriteTrace("Router Service stopping");
        }

求推荐。我遗漏了一些非常小的东西,无法确定。

在调试模式下,应用程序在函数 OnStart 完成后退出。没有什么可以阻止应用程序退出。

你需要添加一个Console.ReadLine();来防止应用程序退出。

#if DEBUG
      EntryPoint service = new EntryPoint();
      service.Start();
      Console.ReadLine();
#else

您可以在 MSDN 阅读更多关于如何:调试 Windows 服务应用程序