Home > other >  Azure Service Bus send messages synchronously
Azure Service Bus send messages synchronously

Time:10-22

I would like to implement something like a monitoring service for the application that already exists. The application will be checking messages in the queues(Azure Service Bus) based on what happened in the main web application. The problem I encountered recently: From what I have seen in the documentation https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview Most of the examples are using asynchronous code (which is totally fine), typically if I am using things such as Entity Framework, I always have option to choose between methods such as _context.Save() and _context.SaveAsync() but unfortunately I could not find examples that support sync code and I know that running async code synchronously is a bad practice. The reason I want to use sync code is simple, the web application is old and there is a lots of code so I could rewrite every possible method to async but that would take ages, instead I would like to send message to service bus synchronously. I am using package Azure.Messaging.ServiceBus and I would like to use

 sender = client.CreateSender(queueName);
  await sender.SendMessagesAsync(messageBatch);

synchronously

CodePudding user response:

The Service Bus client library does not support synchronous operations. In order to use it synchronously, you will need to resort to sync-over-async in your application.

One of the reasons for this design is that the underlying AMQP transport used by the client library is fully asynchronous. To offer a synchronous API, the SDK clients would need to use sync-over-async which wouldn't be apparent to calling applications and would potentially make debugging thread pool issues more difficult for application developers.

CodePudding user response:

The most correct answer is obviously to re-write your code base to follow async / await patterns on all I/O bound calls and reap the benefits of scalability by doing so.

However, since you say you've got a large legacy code base, if you're on .Net Core, you'll be able to provide pseudo sync overloads by using sync-over-async, e.g.:

public static class MyServiceBusExtensions
{
    [Obsolete("TODO - convert our codebase to async")]
    public static void SendMessage(this ServiceBusSender sender, ServiceBusMessage message)
    {
        sender.SendMessageAsync(message, CancellationToken.None).Wait();
    }
}

This will obviously block on the callers thread.

  • Related