.NET Windows Service needs to use STAThread

后端 未结 5 2244
野性不改
野性不改 2020-12-01 08:50

I have created a Windows Service that will be calling out to some COM components, so I tagged [STAThread] to the Main function. However, when the timer fires, it reports MT

5条回答
  •  猫巷女王i
    2020-12-01 09:13

    Looking at a similar example: http://www.aspfree.com/c/a/C-Sharp/Creating-a-Windows-Service-with-C-Sharp-introduction/1/

    What if your main is...

        [STAThread]
        public static void Main ()
        {
            MyMonitor m = new MyMonitor();
            m.Start();
        }
    

    and move your timer start / stop out of the events...

     public void Start() { this.timer.Enabled = true;}
     public void Stop() { this.timer.Enabled = false;}
    
      protected override void OnStart (string[] args)
        {
            EventLog.WriteEntry("MyMonitor", "My Monitor Service Started", EventLogEntryType.Information);
        }
    
        protected override void OnStop ()
        {
            EventLog.WriteEntry("MyMonitor", "My Monitor Service Stopped", EventLogEntryType.Information);
        }
    

提交回复
热议问题