Start multiple instances of the window service

百般思念 提交于 2019-12-25 09:17:00

问题


I have created a windows service that reads an IBM MQ messages and processes them. My Win Service is currently designed OnStart it triggers a timer interval which calls the function that calls the class which does all the work (See code below).

What I am trying to accomplish is to scale (if that is the right word) the application, if there are a lot of messages on the queue to process we would like to run multiple instances/threads of the service. Ideal situation would be to have some type of configuration in the app.config that indicates how many threads or worker processes to have running. Is threading the right approach? Is there a better or preferred way? Right now what we are doing is installing a new instance of the service with a different name and it is getting quiet tedious.

    protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("Service Started", EventLogEntryType.Information);

        _myTimer.Interval = 500; // half a second
        _myTimer.Elapsed += OnTimer;
        _myTimer.AutoReset = false;
        _myTimer.Enabled = true;
    }

    public void OnTimer(object sender, ElapsedEventArgs args)
    {
        //If you want the main program to go ahead and shut down after some period of time, regardless of whether it's obtained the lock, use Monitor.TryEnter. For example, this will wait 15 seconds.
        //bool gotLock = Monitor.TryEnter(_timerLock, TimeSpan.FromSeconds(15));

        if (!Monitor.TryEnter(_timerLock))
        {
            // something has the lock. Probably shutting down.
            return;
        }
        try
        {
            MqSyncJob mqSyncJob = new MqSyncJob(eventLog1);
            mqSyncJob.ProcessSyncJobQueue();                
        }
        catch (Exception ex)
        {
            eventLog1.WriteEntry(ex.ToString(), EventLogEntryType.Error);
        }
        finally
        {
            _myTimer.Start(); // re-enables the timer
            Monitor.Exit(_timerLock);
        }
    }

来源:https://stackoverflow.com/questions/42396090/start-multiple-instances-of-the-window-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!