Microsoft消息传递队列接收事件



我有一个console ceptaiton。在此应用程序中,我与队列联系。首先,我检查一下是否存在名称为" examplequeue"的队列。如果它不存在,我会创建它。创建和恢复路径或仅返回路径后。我想将收款事件附加到此队列。 我有两种可以使用"使用"关键字的方法来使队列在工作后处置了队列,或者我可以使用普通的方式创建队列对象。

在下面您可以看到我的代码:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateQueue(".\exampleQueue", false);
            using (var queue = new MessageQueue(".\exampleQueue"))
            {
                queue.ReceiveCompleted += MyReceiveCompleted;
                queue.BeginReceive();
            }
        }
        public static void CreateQueue(string queuePath, bool transactional)
        {
            if (!MessageQueue.Exists(queuePath))
            {
                MessageQueue.Create(queuePath, transactional);
            }
            else
            {
                Console.WriteLine(queuePath + " already exists.");
            }
        }
        private static void MyReceiveCompleted(Object source,
            ReceiveCompletedEventArgs asyncResult)
        {
            var queue = (MessageQueue)source;
            try
            {
                var msg = queue.EndReceive(asyncResult.AsyncResult);
                Console.WriteLine("Message body: {0}", (string)msg.Body);
                queue.BeginReceive();
            }
            catch (Exception ex)
            {
                var s = ex;
            }
            finally
            {
                queue.BeginReceive();
            }
            return;
        }
    }
}

我面临的问题是,每当我使用此代码来创建队列对象

using (var queue = new MessageQueue(".\exampleQueue"))
            {
                queue.ReceiveCompleted += MyReceiveCompleted;
                queue.BeginReceive();
            }

Myreceivecomplet的事件无法正常工作。但是当我使用此

var queue = new MessageQueue(".\exampleQueue");
            queue.ReceiveCompleted += MyReceiveCompleted;
            queue.BeginReceive();

每件事都以适当的方式工作。

我的问题是哪个是最好的一部分?而且,如果我选择使用第一个Apenocah,我该如何使它起作用?

接受我对不良打字道歉。

您可以使用原始方法,但是您必须确保Main方法在使用语句中阻止:

static void Main(string[] args)
{
    CreateQueue(".\exampleQueue", false);
    using (var queue = new MessageQueue(".\exampleQueue"))
    {
        queue.ReceiveCompleted += MyReceiveCompleted;
        queue.BeginReceive();
        // here you have to insert code to block the 
        // execution of the Main method.
        // Something like:
        while(Console.ReadLine() != "exit")
        {
            // do nothing
        }
    }
}

最新更新