.NET Windows Service needs to use STAThread

后端 未结 5 2229
野性不改
野性不改 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条回答
  •  一生所求
    2020-12-01 08:58

    This reports that it is using STA. It is based on Will's suggestion and http://en.csharp-online.net/Creating_a_.NET_Windows_Service%E2%80%94Alternative_1:_Use_a_Separate_Thread

    using System;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Threading;
    
    
    
    namespace MyMonitorService
    {
        internal class MyMonitorThreaded : ServiceBase
        {
            private Boolean bServiceStarted = false;
            private Thread threadWorker;
    
            private void WorkLoop ()
            {
                while (this.bServiceStarted)
                {
                    EventLog.WriteEntry("MyMonitor", String.Format("Thread Model: {0}", Thread.CurrentThread.GetApartmentState().ToString()), EventLogEntryType.Information);
    
                    if (this.bServiceStarted)
                        Thread.Sleep(new TimeSpan(0, 0, 10));
                }
    
                Thread.CurrentThread.Abort();
            }
    
            #region Service Start/Stop
            protected override void OnStart (String[] args)
            {
                this.threadWorker = new Thread(WorkLoop);
                this.threadWorker.SetApartmentState(ApartmentState.STA);
                this.bServiceStarted = true;
                this.threadWorker.Start();
            }
    
            protected override void OnStop ()
            {
                this.bServiceStarted = false;
                this.threadWorker.Join(new TimeSpan(0, 2, 0));
            }
            #endregion
        }
    }
    

提交回复
热议问题