使用消息泵异步检查 Azure 队列

Asynchronous check of Azure Queues using message pump

在我的应用程序中,我想使用设置的消息泵检查主队列和死信队列。我 运行 遇到的问题是默认实现中的线程。

我不确定如何同时将这两个运行

这是 Azure 消息泵的默认实现

Client.OnMessage((receivedMessage) =>
                {

                }, new OnMessageOptions { AutoComplete = false});
            CompletedEvent.WaitOne()

waitone 方法一直等到 manualResetEvent 设置方法被调用。 我不确定是什么设置了这个方法,我想这是在 onmessage 过程的幕后发生的事情。

现在发生的事情是 onmessage 方法 运行s,它会触发 waitone 进程并一直等待,直到收到另一条消息,这是应该发生的,但我如何获得其中两个 运行同时宁?

也许我没有在关注你的问题,但你在这里得到的是一个用 OnMessage API 注册的回调,如果收到一条消息,你的主程序将继续运行。为什么要在回调之外执行 WaitOne?回调旨在 运行 在后台紧密循环并接收您的消息。

如果您只想接收一两条消息,也许使用 QueueClient(或类似的)是更好的选择?

假设您有一个运行代码的控制台应用程序:

public class Program
{
    private static void Main()
    {
        var completedEvent = new ManualResetEvent(false);
        ...
        var mainQueue = QueueClient.CreateFromConnectionString("MyConnectionString", "MyQueueName");

        mainQueue.OnMessage((receivedMessage) =>
        {

        }, new OnMessageOptions { AutoComplete = false });

        completedEvent.WaitOne();
    }
}

如果您删除 completedEvent.WaitOne();,您的控制台应用程序将立即退出。此行确保您的应用程序不会退出。你可以写一个 while(true) {} 来代替(不推荐,但这是另一个话题)。

消息泵不阻塞电流:这就是为什么您需要阻塞线程(在控制台应用程序、azure webjob、azure worker 角色的情况下)以使您的应用程序不退出。如果您将此代码实现到 windows 服务或 Web 应用程序中,则不必阻塞主线程,因为还有其他机制可以使您的应用程序保持 运行.

当新消息到达时,消息泵启动一个新线程来执行 OnMessage 块内的代码。

所以如果你想同时监听主队列和死信队列,你可以这样做:

public class Program
{
    private static void Main()
    {
        var completedEvent = new ManualResetEvent(false);
        ...
        var mainQueue = QueueClient.CreateFromConnectionString("MyConnectionString", "MyQueueName");
        var deadLetterQueue = QueueClient.CreateFromConnectionString("MyConnectionString", QueueClient.FormatDeadLetterPath("MyQueueName"));

        mainQueue.OnMessage((receivedMessage) =>
        {

        }, new OnMessageOptions { AutoComplete = false });

        deadLetterQueue.OnMessage((receivedMessage) =>
        {

        }, new OnMessageOptions { AutoComplete = false });

        completedEvent.WaitOne();
    }
}