MessageQueue.BeginReceive 如何工作以及如何正确使用它?

Seb*_*ter 4 c# asynchronous msmq message-queue

我目前有一个后台线程。在这个线程中是一个无限循环。

这个循环偶尔会更新数据库中的一些值,然后在 MessageQueue 上侦听 1 秒(使用queue.Receive(TimeSpan.FromSeconds(1)))。

只要没有消息进来,这个调用就会在内部抛出一个 MessageQueueException (Timeout),它被捕获,然后循环继续。如果有消息,调用通常会返回并处理消息,然后循环继续。

这会导致很多第一次机会异常(每秒一次,除非有消息要处理)并且这会导致调试输出垃圾邮件,并且当我忘记排除 MessageQueueExceptions 时也会在调试器中中断。

那么 MessageQueue 的异步处理意味着如何正确完成,同时仍然确保,只要我的应用程序运行,队列就会受到监控,并且数据库也会不时更新。当然这里的线程不应该占用100%的CPU。

我只需要大图或对正确完成异步处理的提示。

Dav*_*ead 5

我建议为 MessageQueue 的 ReceiveCompleted 事件注册一个委托,而不是在线程中循环,如下所述:

using System; using System.Messaging;

namespace MyProject { /// /// Provides a container class for the example. /// public class MyNewQueue {

    //**************************************************
    // Provides an entry point into the application.
    //       
    // This example performs asynchronous receive operation
    // processing.
    //**************************************************

    public static void Main()
    {
        // Create an instance of MessageQueue. Set its formatter.
        MessageQueue myQueue = new MessageQueue(".\\myQueue");
        myQueue.Formatter = new XmlMessageFormatter(new Type[]
            {typeof(String)});

        // Add an event handler for the ReceiveCompleted event.
        myQueue.ReceiveCompleted += new 
            ReceiveCompletedEventHandler(MyReceiveCompleted);

        // Begin the asynchronous receive operation.
        myQueue.BeginReceive();

        // Do other work on the current thread.

        return;
    }


    //**************************************************
    // Provides an event handler for the ReceiveCompleted
    // event.
    //**************************************************

    private static void MyReceiveCompleted(Object source, 
        ReceiveCompletedEventArgs asyncResult)
    {
        // Connect to the queue.
        MessageQueue mq = (MessageQueue)source;

        // End the asynchronous Receive operation.
        Message m = mq.EndReceive(asyncResult.AsyncResult);

        // Display message information on the screen.
        Console.WriteLine("Message: " + (string)m.Body);

        // Restart the asynchronous Receive operation.
        mq.BeginReceive();

        return; 
    }
}
Run Code Online (Sandbox Code Playgroud)

}

来源:https : //docs.microsoft.com/en-us/dotnet/api/system.messaging.messagequeue.receivecompleted?view=netframework-4.7.2