Search code examples
c#azureservicebus

Storing variables in a event-driven message pump?


I'm trying to setup a basic connection to Azure's ServiceBus and have encountered something wierd in Azures examplecode that have kept me wondering over how variables are stored 'cause I can't get that to work.

An example that works:

client.OnMessage(message =>
{
    Console.WriteLine(String.Format("Message body: {0}", message.GetBody<String>()));
    Console.WriteLine(String.Format("Message id: {0}", message.MessageId));
});

If I edit this into something like this:

string test = string.Empty;
client.OnMessage(message =>
{
    test = String.Format("Message body: {0}", message.GetBody<String>());
});
Console.WriteLine("test: "+test); //outputs "test: "

It doesn't work anymore. The output will be just "test: ". Shouldn't this work like this or have I missed something?

Thanks in advance


Solution

  • Your problem is that OnMessage is an event. The lambda expression message => ... executes when a message arrives.

    // keep a list if you need one.
    var bag = new ConcurrentBag<string>();
    // the string is allocated immediately.
    string test = string.Empty;
    // the client will execute the lambda when a message arrives.
    client.OnMessage(message =>
    {
        // this is executed when a message arrives.
        test = String.Format("Message body: {0}", message.GetBody<String>());
    
        // this will output the message when a message arrives, and 
        // the lambda expression executes.
        Console.WriteLine("test: "+test); //outputs "test: "
    
        // you could add the message to a list here.
        bag.Add(message.GetBody<string>());
    });
    
    // this line of code runs immediately, before the message arrives.
    Console.WriteLine("test: "+test); //outputs "test: "