如何检索死信队列计数?

How to retrieve Dead Letter Queue count?

问题

如何在不接收每条消息并计算收到的消息数的情况下获取死信队列长度?

我当前的实现

 public int GetDeadLetterQueueCount()
    {
        //Ref:

        MessagingFactory factory = MessagingFactory.CreateFromConnectionString(CloudConnectionString);

        QueueClient deadLetterClient = factory.CreateQueueClient(QueueClient.FormatDeadLetterPath(_QueueClient.Path), ReceiveMode.PeekLock);
        BrokeredMessage receivedDeadLetterMessage;

        List<string> lstDeadLetterQueue = new List<string>();

        // Ref: https://code.msdn.microsoft.com/Brokered-Messaging-Dead-22536dd8/sourcecode?fileId=123792&pathId=497121593
        // Log the dead-lettered messages that could not be processed:

        while ((receivedDeadLetterMessage = deadLetterClient.Receive(TimeSpan.FromSeconds(10))) != null)
        {
                lstDeadLetterQueue.Add(String.Format("DeadLettering Reason is \"{0}\" and Deadlettering error description is \"{1}\"",
                receivedDeadLetterMessage.Properties["DeadLetterReason"],
                receivedDeadLetterMessage.Properties["DeadLetterErrorDescription"]));
                var locktime = receivedDeadLetterMessage.LockedUntilUtc;
        }

        return lstDeadLetterQueue.Count;
    }

实施问题

因为我在查看和阻止模式下接收每条消息,所以消息设置了锁定持续时间。在此期间,我无法再次收到或什至看到消息,直到这段时间超时。

必须有更简单的方法来获取计数而无需轮询队列吗?

我也不想消费消息,只想统计总金额

您可以使用 NamespaceManager's GetQueue() method which has a MessageCountDetails 属性,它又具有 DeadLetterMessageCount 属性。类似于:

var namespaceManager = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString("<CONN_STRING>");
var messageDetails = namespaceManager.GetQueue("<QUEUE_NAME>").MessageCountDetails;
var deadLetterCount = messageDetails.DeadLetterMessageCount;