The Windows Azure team has recently released Windows Azure Service Bus 2.0.0-beta which lets the Windows Azure developers to use Task based asynchronous operations while working with Windows Azure Service Bus. Now the Windows Windows Azure Service Bus SDK provides Async version for the Service Bus methods. The SDK will be working with both Visual Studio 2010 and Visual Studio 2012 as the SDK compiled against .Net Framework 4.0.
Using async/await with Windows Azure Service Bus
You can add the beta version of Azure Service Bus SDK using NuGet. Since the updated Service Bus SDK is just reached Beta, you have to specify the “Include Prerelease” option in the Manage NuGet windows as shown in the following picture.
The following code block shows the usage of aync/await with Service Bus Queue operations.
1: public static async Task<QueueClient> GetQueueClientAsync ()
3: QueueClient client;
4: string connectionString =
7: NamespaceManager namespaceManager = CreateNamespaceManager();
8: //Create the queue if it does not exists
9: if (!(await namespaceManager.QueueExistsAsync(QueueName)))
11: await namespaceManager.CreateQueueAsync(QueueName);
13: // Initialize the connection to Service Bus Queue
14: client = QueueClient.CreateFromConnectionString
15: (connectionString, QueueName);
16: return client;
In above code block, we are using async operations of QueueExists method and CreateQueue methods along with the await keyword. In the below code block, we are calling the above GetQueueClientAsync method and asynchronously sending messages to Service Bus Queue.
1: public async Task<ActionResult> Submit(OnlineOrder order)
3: if (ModelState.IsValid)
5: // Create a message from the order
6: var message = new BrokeredMessage(order);
7: // Getting the Queue
8: QueueClient queueClient =
9: await QueueConnector.GetQueueClientAsync();
10: // Submit the order
11: await queueClient.SendAsync(message);
12: return RedirectToAction("Submit");
16: return View(order);
The messages retrieving from Service Bus Queue as shown in the code block provided below.
1: // Receive the message
2: BrokeredMessage receivedMessage = null;
3: receivedMessage =await Client.ReceiveAsync();
4: if (receivedMessage != null)
6: // Process the message
9: // View the message as an OnlineOrder
10: OnlineOrder order = receivedMessage.GetBody<OnlineOrder>();
11: Trace.WriteLine(order.Customer + ": " +
12: order.Product, "ProcessingMessage");
13: await receivedMessage.CompleteAsync();