4

我对 MSMQ 和 .NET 中的线程都比较陌生。我必须创建一个在不同线程中侦听的服务,通过 TCP 和 SNMP、多个网络设备和所有这些东西在专用线程中运行,但这里还需要从其他应用程序侦听 MSMQ 队列。我正在分析另一个类似的项目,并且使用了下一个逻辑:

private void MSMQRetrievalProc()
{
    try
    {
        Message mes;
        WaitHandle[] handles = new WaitHandle[1] { exitEvent };
        while (!exitEvent.WaitOne(0, false))
        {
            try
            {
                mes = MyQueue.Receive(new TimeSpan(0, 0, 1));
                HandleMessage(mes);
            }
            catch (MessageQueueException)
            {
            }
        }
    }
    catch (Exception Ex)
    {
        //Handle Ex
    }
}

MSMQRetrievalThread = new Thread(MSMQRetrievalProc);
MSMQRetrievalThread.Start();

但是在另一个服务(消息调度程序)中,我使用了基于MSDN 示例的异步消息读取:

public RootClass() //constructor of Main Class
{
    MyQ = CreateQ(@".\Private$\MyQ"); //Get or create MSMQ Queue

    // Add an event handler for the ReceiveCompleted event.
    MyQ.ReceiveCompleted += new
ReceiveCompletedEventHandler(MsgReceiveCompleted);
    // Begin the asynchronous receive operation.
    MyQ.BeginReceive();
}

private void MsgReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
{

    try
    {
        // Connect to the queue.
        MessageQueue mq = (MessageQueue)source;
        // End the asynchronous Receive operation.
        Message m = mq.EndReceive(asyncResult.AsyncResult);

        // Process received message

        // Restart the asynchronous Receive operation.
        mq.BeginReceive();
    }
    catch (MessageQueueException Ex)
    {
        // Handle sources of MessageQueueException.
    }
    return;
}

异步处理是否假设每条消息都将在主线程之外处理?可以并且需要将这种(第二种)方法放在单独的线程中吗?

请建议更好的方法或一些简单的替代方案。

到达队列的消息没有一些规则定义的行为。可能很长一段时间内没有任何消息会到达,或者在一秒钟内我会到达许多(最多 10 条甚至更多)消息。根据某些消息中定义的操作,它需要删除/更改一些具有正在运行的线程的对象。

4

1 回答 1

1

我强烈建议将 WCF 用于 MSMQ。

http://msdn.microsoft.com/en-us/library/ms789048.aspx

这允许您使用 WCF 线程模型异步处理传入调用,该模型允许限制、封顶、重试等......

于 2012-09-22T00:20:52.647 回答