c# - 在多线程服务中监听的更好方法是什么?

标签 c# .net multithreading thread-safety msmq

我对 .NET 中的 MSMQ 和线程处理都比较陌生。我必须创建一个服务,通过 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 Example 的异步消息读取:

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 条甚至更多)消息。根据某些消息中定义的操作,它需要删除/更改一些具有运行线程的对象。

最佳答案

我强烈建议为 MSMQ 使用 WCF。

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

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

关于c# - 在多线程服务中监听的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458065/

相关文章:

c# - FlowDocument 强制分页 (BreakPageBefore)

时间:2019-03-07 标签:c#awaitabletask留在相同的上下文中

c# - 如何使用 C#/IHTMLDocument2 设置文本字段的值

c# - 开发一个简单的 Windows 系统托盘桌面应用程序以使用 .NET Web 服务

c# - 如何在 c#/winforms 中将图像裁剪成圆形?

.net - 跟踪复杂对象图中的变化

c# - 线程执行时序

java - 停止可能永远循环的线程

c# - 只读变量线程安全吗?

c# - mvvm 中的 ComboBox 静态值绑定(bind)