In this example. When I run this in the console, I dont get anything in MyList property so nothing is displayed on the screen. BUT, if I add a breakpoint, I do get the expected content in the list. Possibly because the method where MyList is populated is an async.. and the process of adding to list is a sync? How would you change this code so that MyList is always populated when Program runs?
namespace ReceiverApp
{
static class Program
{
public static List<string> MyList { get; set; }
const string ServiceBusConnectionString = "Endpoint=sb://...";
const string QueueName = "...";
static IQueueClient queueClient;
static void Main(string[] args)
{
MyList = new List<string>();
MainAsync().GetAwaiter().GetResult();
foreach (var item in MyList)
{
Console.WriteLine(item);
}
}
static async Task MainAsync()
{
queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
RegisterOnMessageHandlerAndReceiveMessages();
await queueClient.CloseAsync();
}
static void RegisterOnMessageHandlerAndReceiveMessages()
{
var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
{
MaxConcurrentCalls = 1,
AutoComplete = false
};
queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
}
static async Task ProcessMessagesAsync(Message message, CancellationToken token)
{
// Process the message
MyList.Add(Encoding.UTF8.GetString(message.Body));
//await queueClient.CompleteAsync(message.SystemProperties.LockToken);
}
static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs args)
{
Console.WriteLine($"Message handler encountered an exception {args.Exception}.");
return Task.CompletedTask;
}
}
}