C# 在多线程服务中监听的更好方法是什么?
我对MSMQ和.NET中的线程都比较陌生。我必须创建一个服务,通过TCP和SNMP在不同的线程中侦听,几个网络设备和所有这些东西在专用线程中运行,但这里还需要侦听来自其他应用程序的MSMQ队列。 我正在分析另一个类似的项目,下一个逻辑是:C# 在多线程服务中监听的更好方法是什么?,c#,.net,multithreading,thread-safety,msmq,C#,.net,Multithreading,Thread Safety,Msmq,我对MSMQ和.NET中的线程都比较陌生。我必须创建一个服务,通过TCP和SNMP在不同的线程中侦听,几个网络设备和所有这些东西在专用线程中运行,但这里还需要侦听来自其他应用程序的MSMQ队列。 我正在分析另一个类似的项目,下一个逻辑是: private void MSMQRetrievalProc() { try { Message mes; WaitHandle[] handles = new WaitHandle[1] { exitEvent
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();
但在另一个服务(message dispatcher)中,我使用了异步消息读取,基于:
异步处理是否假设每个消息都将在主线程之外的其他线程中处理?
这种(第二种)方法是否可以并且需要放在单独的线程中
请建议更好的方法或一些简单的选择
到达队列的消息没有某些规则定义的行为。这可能是因为很长一段时间内没有任何否定的信息会到达,或者在一秒钟内有许多(多达10条或更多)的信息到达。根据某些消息中定义的操作,它将需要删除/更改具有运行线程的某些对象 我强烈建议对MSMQ使用WCF
这允许您使用WCF线程模型异步处理传入呼叫,该模型允许节流、封顶、重试等。谢谢@Tom Anderson,但我仅限于.NET2.0,其中一个消息主题是Delphi应用程序-似乎无法将WCF应用于MSMQ
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;
}