gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:49:08 26 4
gpt4 key购买 nike

我对 .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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com