【问题标题】:Methods in Windows Service not working as Timer eventsWindows 服务中的方法不能用作计时器事件
【发布时间】:2023-01-20 20:46:03
【问题描述】:

我正在创建这个简单的 Windows 服务以每六秒播放一次蜂鸣声。当我在调试模式下启动它时,它会在启动后立即停止。似乎没有错误或异常。

 public partial class Service1 : ServiceBase
    {
        static Timer myTimer;
        public Service1()
        {
            InitializeComponent();
        }

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

        protected override void OnStart( string[] args )
        {

            myTimer = new Timer();
            myTimer.AutoReset = true;
            myTimer.Interval = 60000;
            myTimer.Enabled = true;
            myTimer.Start();

            myTimer.Elapsed += new ElapsedEventHandler( OnTimedEvent );

        }

        private static void OnTimedEvent( object sender, ElapsedEventArgs e )
        {
                SystemSounds.Beep.Play();
        }

        protected override void OnStop()
        {
        }


    }

我的主要方法

static void Main()
{
#if DEBUG
    Service1 testService = new Service1();
    testService.OnDebug();

#else
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new Service1()
    };
    ServiceBase.Run(ServicesToRun);
#endif
}

哔哔声本身就可以正常工作。但它不适用于计时器。

【问题讨论】:

  • 你能展示你的主要方法吗?

标签: c# timer windows-services


【解决方案1】:

您需要继续运行您的服务,您可以在行testService.OnDebug(); 之后添加此代码。它将使您的服务运行,直到您按 q。

Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;

【讨论】:

  • 谢谢!它运作良好。另外,我将输出模式更改为Console Application
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多