2015-05-09 102 views
-1

我有一个控制台应用程序。在这个应用程序中,我会联系一个队列。首先我检查是否存在例如名称为'exampleQueue'的队列是否存在。如果它不存在,我创建它。 之后创建和returing路径或只是返回路径。我想将ReceiveCompleted事件附加到此队列中。 我有两种方法,我可以使用'使用'关键字使我的工作后排队的队列,或者我可以使用正常的方式来创建队列对象。Microsoft消息队列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(); 

每一件事只是在适当的方式工作。

我的问题是哪个程序是最好的? 如果我选择使用第一个程序,我该如何使它工作?

接受我的不好打字的道歉。

+0

您的队列对象将是由垃圾收集清理。 using语句导致立即调用dispose。将您的队列变量更改为程序类的静态变量。基本上队列正在清理之前,你的事件可以触发。 – Nattrass

+0

tnx你的答案。我不知道我是否没有处理我的对象。它在生产使用中会成为问题吗?我的意思是说,在1周或1个月之后,该对象不会影响性能? – elhampour

+0

是的,垃圾收集器仍然会在将来某个未确定的点上垃圾你的队列对象,并且你的ReceiveCompleted事件不会触发。 – Nattrass

回答

1

您可以使用原来的做法,但你必须确保,该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 
     } 
    } 
}