多线程Windows服务,用于处理Windows Message Queue

时间:2015-11-14 06:15:08

标签: c# multithreading windows-services

这是我第一次尝试编写Windows服务。

此Windows服务必须处理2个Windows消息队列。

每个Message Queue都应该有自己的主题,但我似乎无法让架构到位。

我遵循了Windows Service to run constantly这允许我创建一个我处理一个队列的线程。

所以这是我的服务类:

    protected override void OnStart(string[] args)
    {
        _thread = new Thread(WorkerThreadFunc) { Name = "Address Calculator Thread", IsBackground = true };
        _thread.Start();
    }

    private void WorkerThreadFunc()
    {
        _addressCalculator = new GACAddressCalculator();

        while (!_shutdownEvent.WaitOne(0))
        {
            _addressCalculator.StartAddressCalculation();
        }
    }



    protected override void OnStop()
    {
        _shutdownEvent.Set();
        if (!_thread.Join(5000))
        { // give the thread 5 seconds to stop
            _thread.Abort();
        }
    }

在我的GACAddressCalculator.StartAddressCalculation()我正在创建一个如下所示的队列处理器对象:

    public void StartAddressCalculation()
    {
        try
        {
            var googleQueue = new GISGoogleQueue("VehMonLogGISGoogle", 1, _gacLogger, 1);
            googleQueue.ProccessMessageQueue();

        }
        catch (Exception ex)
        {

        }

    }

这是GISGoogleQueue

public class GISGoogleQueue : BaseMessageQueue
{


    public GISGoogleQueue(string queueName, int threadCount, GACLogger logger, int messagesPerThread)
        : base(queueName, threadCount, logger, messagesPerThread)
    {
    }

    public override void ProccessMessageQueue()
    {
        if (!MessageQueue.Exists(base.QueueName))
        {
            _logger.LogMessage(MessageType.Information, string.Format("Queue '{0}' doesn't exist", this.QueueName));
            return;
        }

        var messageQueue = new MessageQueue(QueueName);
        var myVehMonLog = new VehMonLog();
        var o = new Object();
        var arrTypes = new Type[2];
        arrTypes[0] = myVehMonLog.GetType();
        arrTypes[1] = o.GetType();
        messageQueue.Formatter = new XmlMessageFormatter(arrTypes);

        using (var pool = new Pool(ThreadCount))
        {

            // Infinite loop to process all messages in Queue
            for (; ; )
            {
                for (var i = 0; i < MessagesPerThread; i++)
                {
                    try
                    {
                        while (pool.TaskCount() >= MessagesPerThread) ; // Stop execution until Tasks in pool have been executed


                        var message = messageQueue.Receive(new TimeSpan(0, 0, 5, 0)); // TimeOut for message reading from Queue, set to 5 minutes, Will throw exception after 5 mins

                        if (message != null) // Check if message is not Null
                        {
                            var monLog = (VehMonLog)message.Body;
                            pool.QueueTask(() => ProcessMessageFromQueue(monLog)); // Add to Tasks list in Pool
                        }

                    }
                    catch (Exception ex)
                    {

                    }

                }
            }
        }
    }

}

现在这适用于1个消息队列,但是如果我想处理另一个消息队列,它就不会发生,因为我在ProccessMessageQueue方法中有一个无限循环。

我想在一个单独的线程中执行每个队列。

我认为我在WorkerThreadFunc()犯了一个错误,我必须以某种方式从那里或OnStart()开始两个主题。

此外,如果您有任何关于如何改进此服务的提示会很棒。

顺便说一句,我使用此答案https://stackoverflow.com/a/436552/1910735中的Pool Class作为ProccessMessageQueue

内的线程池

2 个答案:

答案 0 :(得分:2)

我建议您更改服务类如下(以下评论):

protected override void OnStart(string[] args)
{
    _thread = new Thread(WorkerThreadFunc)
              {
                  Name = "Run Constantly Thread",
                  IsBackground = true
              };
    _thread.Start();
}

GISGoogleQueue _googleQueue1;
GISGoogleQueue _googleQueue2;
private void WorkerThreadFunc()
{
    // This thread is exclusively used to keep the service running.
    // As such, there's no real need for a while loop here.  Create
    // the necessary objects, start them, wait for shutdown, and
    // cleanup.
    _googleQueue1 = new GISGoogleQueue(...);
    _googleQueue1.Start();
    _googleQueue2 = new GISGoogleQueue(...);
    _googleQueue2.Start();

    _shutdownEvent.WaitOne();  // infinite wait

    _googleQueue1.Shutdown();
    _googleQueue2.Shutdown();
}

protected override void OnStop()
{
    _shutdownEvent.Set();
    if (!_thread.Join(5000))
    {
        // give the thread 5 seconds to stop
        _thread.Abort();
    }
}

我忽略了你的GACAddressCalculator。根据你展示的内容,它似乎是GISGoogleQueue周围的薄包装。显然,如果它实际上做了一些你没有表现出来的东西,那么它需要被重新考虑。

请注意,GISGoogleQueue中创建了两个WorkerThreadFunc()个对象。接下来让我们看看如何创建这些对象以实现适当的线程模型。

public class GISGoogleQueue : BaseMessageQueue
{
    System.Threading.Thread _thread;
    System.Threading.ManualResetEvent _shutdownEvent;

    public GISGoogleQueue(string queueName, int threadCount, GACLogger logger, int messagesPerThread)
         : base(queueName, threadCount, logger, messagesPerThread)
    {
        // Let this class wrap a thread object.  Create it here.
        _thread = new Thread(RunMessageQueueFunc()
                  {
                      Name = "Run Message Queue Thread " + Guid.NewGuid().ToString(),
                      IsBackground = true
                  };
        _shutdownEvent = new ManualResetEvent(false);
    }

    public Start()
    {
        _thread.Start();
    }

    public Shutdown()
    {
        _shutdownEvent.Set();
        if (!_thread.Join(5000))
        {
            // give the thread 5 seconds to stop
            _thread.Abort();
        }
    }

    private void RunMessageQueueFunc()
    {
        if (!MessageQueue.Exists(base.QueueName))
        {
            _logger.LogMessage(MessageType.Information, string.Format("Queue '{0}' doesn't exist", this.QueueName));
            return;
        }

        var messageQueue = new MessageQueue(QueueName);
        var myVehMonLog = new VehMonLog();
        var o = new Object();
        var arrTypes = new Type[2];
        arrTypes[0] = myVehMonLog.GetType();
        arrTypes[1] = o.GetType();
        messageQueue.Formatter = new XmlMessageFormatter(arrTypes);

        using (var pool = new Pool(ThreadCount))
        {
            // Here's where we'll wait for the shutdown event to occur.
            while (!_shutdownEvent.WaitOne(0))
            {
                for (var i = 0; i < MessagesPerThread; i++)
                {
                    try
                    {
                        // Stop execution until Tasks in pool have been executed
                        while (pool.TaskCount() >= MessagesPerThread) ;

                        // TimeOut for message reading from Queue, set to 5 minutes, Will throw exception after 5 mins
                        var message = messageQueue.Receive(new TimeSpan(0, 0, 5, 0));

                        if (message != null) // Check if message is not Null
                        {
                            var monLog = (VehMonLog)message.Body;
                            pool.QueueTask(() => ProcessMessageFromQueue(monLog)); // Add to Tasks list in Pool
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
    }
}

这种方法围绕使用由Thread类包装的GISGoogleQueue对象。对于您创建的每个GISGoogleQueue对象,您将获得一个包装线程,该线程将在Start()对象上调用GISGoogleQueue后执行该工作。

有几点。在RunMessageQueueFunc()中,您需要检查是否存在队列名称。如果没有,则退出该功能。发生 IF 时,线程也会退出。关键是你可能希望在此过程的早期检查。只是一个想法。

其次,请注意您的无限循环已被对_shutdownEvent对象的检查所取代。这样,当服务关闭时,循环将停止。为了及时性,您需要确保完整的循环过程不会花费太长时间。否则,您可能会在关机后5秒内终止中断线程。中止只是为了确保事情被拆除,但如果可能的话应该避免。

我知道很多人会更喜欢使用Task类来做这样的事情。您似乎在RunMessageQueueFunc()内。但是对于在进程持续时间内运行的线程,我认为Task类是错误的选择,因为它会占用线程池中的线程。对我来说,Thread类是为什么构建的。

HTH

答案 1 :(得分:0)

您可以像这样使用Parallel.ForEach;

 Parallel.ForEach(queueItems, ProcessQueue); //this will process each queue item in a separate thread


 private void ProcessQueue(QueueItem queue)
 {
     //your processing logic       
 }