2013-01-03 27 views
3

我有一個調用來獲取失敗的MSMQ的計數。「打開」一個MSMQ與.net

經過一番研究,我發現這個問題:Reading MSMQ message count with ruby

答案有指示,如果隊列是空的,封閉,你不能獲得「績效指標」(包括消息計數)。

所以我現在的問題是,我如何以編程方式「打開」(即「關閉」)使用.NET和C#的MSMQ?


更新:櫃面它是相關的,這裏是我的代碼來獲取消息計數:上queue.Init發生

private static int GetMessageCount(string queueName, string machine) 
{ 
    MSMQManagement queue = new MSMQManagement(); 

    string formatName = @"DIRECT=OS:" + machine + @"\PRIVATE$\" + queueName; 
    queue.Init(machine, null, formatName); 
    return queue.MessageCount; 
} 

錯誤。錯誤消息是:「該隊列未打開或可能不存在。」

此代碼在另一個設置相同(但不爲空)的隊列上工作得很好。

+0

這太問題有一個博客鏈接,描述我所看到的方式(雖然不是很大,如果許多消息的答案可以在隊列中)http://stackoverflow.com/questions/2619208/is-there-a-better-way-to-count-the-messages-in-an-message-queue-msmq另外,這調查一些方法http://www.codeproject.com/Articles/346575/Message-Queue-Counting-Comparisions – hatchet

回答

3

要解決的「隊列未打開」的錯誤,你可以通過使用標準MSMQ調用打開隊列,但該消息偷看的小超時。您必須捕獲超時異常「請求的操作超時已過期。」但超時後,你可以查詢隊列與MSMQManagement對象,即使它有0消息:

 MSMQ.MSMQApplication q = new MSMQ.MSMQApplication(); 
     object obj = q.ActiveQueues; 
     foreach (object oFormat in (object[])q.ActiveQueues) 
     { 
      object oMissing = Type.Missing; 
      object oMachine = System.Environment.MachineName; 
      MSMQ.MSMQManagement qMgmt = new MSMQ.MSMQManagement(); 
      object oFormatName = oFormat; // oFormat is read only and we need to use ref 
      qMgmt.Init(ref oMachine, ref oMissing, ref oFormatName); 
      outPlace.Text += string.Format("{0} has {1} messages queued \n", oFormatName.ToString(), qMgmt.MessageCount.ToString()); 
     } 
     foreach (object oFormat in (object[])q.PrivateQueues) 
     { 
      object oMissing = Type.Missing; 
      object oMachine = System.Environment.MachineName; 
      MSMQ.MSMQManagement qMgmt = new MSMQ.MSMQManagement(); 
      queue = new MessageQueue(oFormat.ToString()); 
      object oFormatName = queue.FormatName; // oFormat is read only and we need to use ref 
      TimeSpan timeout=new TimeSpan(2); 
      try 
      { 
       Message msg = queue.Peek(timeout); 
      } 
      catch 
      {// being lazy and catching everything for this example 
      } 
      qMgmt.Init(ref oMachine, ref oMissing, ref oFormatName); 
       outPlace.Text += string.Format("{0} {1} {2}\n", oFormat.ToString(), queue.FormatName.ToString(), qMgmt.MessageCount.ToString()); 
     } 
    }