Introduction
Let's take advantage of the previous article, “Send a Brokered Message to Azure Service Bus” to leverage the same working program to compare send and sendAsync methods. We will try to send messages for a duration of one minute and then determine the actual number of messages that were sent within that minute.
Step 1: Synchronous Send
The code snippet to send the same object using the synchronous send method to the Azure Service Bus for one minute is as outlined below:
- private void SendMessageBySend(MessageSender sender, Employee employee)
- {
- var stopwatch = new Stopwatch();
- stopwatch.Start();
- int count = 0;
- while (stopwatch.Elapsed < TimeSpan.FromSeconds(60))
- {
- count++;
- BrokeredMessage brokeredMessage = new BrokeredMessage(employee);
- sender.Send(brokeredMessage);
- brokeredMessage.Dispose();
- Console.WriteLine(string.Format("Number of messages sent - {0}, Time elapsed (in milliseconds) - {1}",
count.ToString(), stopwatch.ElapsedMilliseconds.ToString()));
- }
- stopwatch.Stop();
- Console.WriteLine("Total number of message sent using send()
- method. Total -> " + count);
- Console.ReadLine();
- }
the the total number of messages sent within that minute is as shown in the following:
Step 2: Asynchronous Send
The code snippet to send the same object using the asynchronous send method to the Azure Service Bus for one minute is as outlined below:
- private void SendMessageBySendAsync(MessageSender sender, Employee employee)
- {
- var stopwatch = new Stopwatch();
- stopwatch.Start();
- int count = 0;
- while (stopwatch.Elapsed < TimeSpan.FromSeconds(60))
- {
- count++;
- BrokeredMessage brokeredMessage = new BrokeredMessage(employee);
- sender.SendAsync(brokeredMessage);
- brokeredMessage.Dispose();
- Console.WriteLine(string.Format("Number of messages sent - {0}, Time elapsed (in milliseconds) - {1}",
count.ToString(), stopwatch.ElapsedMilliseconds.ToString()));
- }
- stopwatch.Stop();
- Console.WriteLine("Total number of message sent using sendAsync() method. Total -> " + count);
- Console.ReadLine();
- }
The total number of messages sent within that minute is as shown in the following:
Conclusion
This is a minor comparison between synchronous and asynchronous processing. In situations where high volume occurs, utilizing asynchronous processing is preferred. A code sample has been attached. Note: in the event that you experience an out of memory exception, simply reduce the duration and execute it again.
Happy coding!