Implementing SendBatchAsync for Microsoft Azure Service Bus Brokered Messages

955 Views Asked by At

My requirement is that I have to send a list of brokered messages to the azure service bus asynchronously. However I am not able to implement the SendBatchAsync method properly. Let me explain in detail. Here is my code:

public async Task SendBatchEnrollmentMessages()
{
    while(somevalue) 
    {
        //logic to fetch data from the SQL db through stored proc into list of brokered message i.e. messageList
        if(messageList.Count() > 0)
        {
            await sender.SendMessagesAsync(messageList);
        } 
        //some more logic for somevalue
    }
}

where the SendMessageAsync logic is :

public async Task SendMessagesAsync(List<BrokeredMessage> brokeredMessageList)
{
    var topicClient = CreateTopicClient();
    await topicClient.SendBatchAsync(brokeredMessageList);
}

My issue is that when I debug the application using break point, the compiler comes till await topicClient.SendBatchAsync(brokeredMessageList); and exits the code i.e application debuggin is completed. It doesn't return back to the while condition. However instead of using SendBatchAsync if I use SendBatch, it works fine. What am I doing wrong?

Solution: The issue was with the test method which was calling the above funciton. It was of type void. It should have been of type async Task. A big thanks to Ned Stoyanov for helping me out in this.

1

There are 1 best solutions below

7
On BEST ANSWER

An async method returns when after encounters an await statement and sets up the asynchronous operation being awaited. The rest of the method then continues after the await is finished.

You probably can't step through async methods like that, but try putting a breakpoint after the await and it should get hit when the asynchronous call completes.

Alternatively you may have a deadlock, see this post for some ways to avoid it.

As mentioned in our discussion the unit test needs to be async as well, return a Task and await any async calls

[TestMethod] 
public async Task SendRegionsEnrollmentMessages() 
{ 
    EventManager eventMgr = new EventManager(clientUrn, programUrn, "CW"); 
    await eventMgr.SendBatchEvents(EventType.ENROLLMENT); 
}