Azure Service Bus“ReceiveAsync”

时间:2018-05-21 03:57:25

标签: c# azure azureservicebus azure-servicebus-queues

是否有办法使用Microsoft.Azure.ServiceBus包来等待当前线程从队列接收消息?

这可能更符合我的理解和希望以不打算使用的方式使用该技术,但我想要做的是结合来自the following Microsoft example的发送和接收示例这样你就可以将消息发送到各种队列,并能够监听并处理“回复”(只是你正在队列中收听的消息),并在收到消息后关闭连接。 / p>

这里有一些伪代码:

   // send message(s) that will be consumed by other processes / applications, and by doing so later on we will expect some messages back
   await SendMessagesAsync(numberOfMessages);

    var receivedMessages = 0;
    while (receivedMessages < numberOfMessages)
    {
        // there is no "ReceiveAsync" method, this is what I would be looking for
        Message message = await queueClient.ReceiveAsync(TimeSpan.FromSeconds(30));
        receivedMessages++;

        // do something with the message here
   }

   await queueClient.CloseAsync();

这可能还是我“做错了”?

2 个答案:

答案 0 :(得分:1)

ReceiveAsync类中可以使用MessageReceiver方法{/ 1}}方法:

var messageReceiver = new MessageReceiver(SBConnString, QueueName, ReceiveMode.PeekLock);
Message message = await messageReceiver.ReceiveAsync();

请参阅Get started sending and receiving messages from Service Bus queues using MessageSender and MessageReceiver上的完整示例。

答案 1 :(得分:0)

Microsoft.Azure.ServiceBus库中,没有这样的东西ReceiveAsync。在这种情况下,您可以使用RegisterOnMessageHandlerAndReceiveMessages()处理或接收消息。这样,您可以接收带有事件的消息。像RegisterOnMessageHandlerAndReceiveMessages()这样的queueClient.RegisterMessageHandler(ReceiveOrProcessMessagesAsync, messageHandlerOptions);,您必须分别为receiveMessages创建此事件,在我们的例子中是ReceiveOrProcessMessagesAsync

static async Task ReceiveOrProcessMessagesAsync(Message message, CancellationToken token)
    {
        // Process the message
        Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

        // Complete the message so that it is not received again.
        // This can be done only if the queueClient is created in ReceiveMode.PeekLock mode (which is default).
        await queueClient.CompleteAsync(message.SystemProperties.LockToken);

        // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
        // If queueClient has already been Closed, you may chose to not call CompleteAsync() or AbandonAsync() etc. calls 
       // to avoid unnecessary exceptions.
    }

,您可以参考下面的链接以了解有关Microsoft.Azure.ServiceBus的信息 https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues

相关问题