Search code examples
.netazureazureservicebusazure-servicebus-queues

Azure Service Bus Nothing Happens When I Send Message


I have set up an Azure Service Bus and a class using Microsoft's Azure Service Bus documentation as a template. When I try running my code nothing happens. No messages are sent to the service bus. I tried breaking it with incorrect queue name and connection string and didn't even get an error. I am new to Async programming so maybe I am not properly implementing my tasks.

    public static async Task SendMessageAsync(string messageToSend)
    {
        // create a sender Bus Client
        ServiceBusClient client = new ServiceBusClient(connectionString);
        
        // create a sender for the queue.
        ServiceBusSender sender = client.CreateSender(queueName);

        // create a message that we can send. 
        ServiceBusMessage message = new ServiceBusMessage(messageToSend);

        // send the message
        await sender.SendMessageAsync(message);
        Console.WriteLine($"Sent a single message to the queue: {queueName}");

        await client.DisposeAsync();            
    }

Calling this method here:

    private void ProcessPerformanceContributionFeed(string[] args, string batchRunId)
    {
        
        var task1 = Task.Run(async() =>  await AzureServiceBusHelper.SendMessageAsync($"Performance Contribution Started at {DateTime.Now.ToString()}"));

The tasks runs (I think?) without any errors or any messages being sent to the Service Bus.


Solution

  • I believe you're running into this issue is because you're not waiting for the task to complete.

    Please change the following line of code:

    var task1 = Task.Run(async() =>  await AzureServiceBusHelper.SendMessageAsync($"Performance Contribution Started at {DateTime.Now.ToString()}"));
    

    to

    var task1 = Task.Run(async() =>  await AzureServiceBusHelper.SendMessageAsync($"Performance Contribution Started at {DateTime.Now.ToString()}"));
    task1.Wait();
    

    and your problem should be fixed.

    More information on Task.Wait can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.wait?view=net-5.0.