-1

我有一个控制台应用程序。在这个应用程序中,我与队列联系。首先,我检查例如名称为“exampleQueue”的队列是否存在。如果它不存在,我创建它。在创建和返回路径或只是返回路径之后。我想将 ReceiveCompleted 事件附加到此队列。我有两种方法,我可以使用“使用”关键字在工作后处理队列,或者我可以使用普通方式创建队列对象。

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

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();
            }

MyReceiveCompleted 事件无法正常工作。但是当我使用这个

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

每件事都以正确的方式工作。

我的问题是哪个方法是最好的?如果我选择使用第一个 appprocah,我怎样才能让它工作?

接受我对打字错误的道歉。

4

1 回答 1

1

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

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
        }
    }
}
于 2015-05-09T11:31:07.867 回答