相关疑难解决方法(0)

.NET Windows服务需要使用STAThread

我创建了一个将调用某些COM组件的Windows服务,因此我将[STAThread]标记为Main函数.但是,当计时器触发时,它会报告MTA并且COM调用失败.我怎样才能解决这个问题?

using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Timers;



namespace MyMonitorService
{
    public class MyMonitor : ServiceBase
    {
        #region Members
        private System.Timers.Timer timer = new System.Timers.Timer();
        #endregion

        #region Construction
        public MyMonitor ()
        {
            this.timer.Interval = 10000; // set for 10 seconds
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
        }
        #endregion

        private void timer_Elapsed (object sender, ElapsedEventArgs e)
        {
            EventLog.WriteEntry("MyMonitor", String.Format("Thread Model: {0}", Thread.CurrentThread.GetApartmentState().ToString()), EventLogEntryType.Information);
        }

        #region Service Start/Stop
        [STAThread]
        public static void Main ()
        {
            ServiceBase.Run(new MyMonitor());
        }

        protected override void …
Run Code Online (Sandbox Code Playgroud)

.net windows-services sta

14
推荐指数
3
解决办法
2万
查看次数

标签 统计

.net ×1

sta ×1

windows-services ×1