Azure Service Bus SendMessageAsync method terminates and crashes whole program

Viewed 50

I created a .NET core 6 project. I added Azure.Messaging.ServiceBus as the dependency. I am using below code to send message to service bus topic.

   // See https://aka.ms/new-console-template for more information
using Azure.Messaging.ServiceBus;
using System.Dynamic;
using System.Net;
using System.Text;
using System.Text.Json;

Console.WriteLine("Hello, World!");

Sender t = new Sender();
Sender.Send();

class Sender
{
  
public static async Task Send()
{
    string connectionString = "Endpoint=sb://sb-test-one.servicebus.windows.net/;SharedAccessKeyName=manage;SharedAccessKey=8e+6SWp3skB3AeDlwH6ufGEainEs45353435JzDywz5DU=;";
    string topicName = "topicone";
    string subscriptionName = "subone";

    // The Service Bus client types are safe to cache and use as a singleton for the lifetime
    try
    {

        await using var client = new ServiceBusClient(connectionString, new ServiceBusClientOptions
        {
            TransportType = ServiceBusTransportType.AmqpWebSockets
        });

        // create the sender
        ServiceBusSender sender = client.CreateSender(topicName);
        dynamic data = new ExpandoObject();
        data.name = "Abc";
        data.age = 6;

        // create a message that we can send. UTF-8 encoding is used when providing a string.
        
        var messageBody = JsonSerializer.Serialize(data);
        
        ServiceBusMessage message = new ServiceBusMessage(messageBody);
        // send the message
        await sender.SendMessageAsync(message);

       
        var s = 10;

    }
    catch (Exception e)
    {
        var v = 10;
    }

    //// create a receiver for our subscription that we can use to receive the message
    //ServiceBusReceiver receiver = client.CreateReceiver(topicName, subscriptionName);

    //// the received message is a different type as it contains some service set properties
    //ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();

    //// get the message body as a string
    //string body = receivedMessage.Body.ToString();
    //Console.WriteLine(body);

    Console.WriteLine("Press any key to end the application");
    Console.ReadKey();
    }
}

Issue: When I call await sender.SendMessageAsync(message); after this line get executed, the program is actually terminating. It not awating. The whole execution stops after this line.

System is not throwing any exception and service bus is not receiving any message.

I just noticed that all other samples I saw had a default SharedAccessPolicy called RootManageSharedAccessKey policy available by default in the azure portal. For me, I had to create this policy. To my policy I have given Manage, Send, ReceiveAccess.

1 Answers

Needed to change Sender.Send(); to Sender.Send().GetAwaiter().GetResult();

Related