在事件驱动的消息泵中存储变量?

Storing variables in a event-driven message pump?

我正在尝试建立与 Azure 的 ServiceBus 的基本连接,但在 Azure 的示例代码中遇到了一些奇怪的事情,这让我一直想知道变量是如何存储的,因为我无法让它工作。

一个有效的例子:

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

如果我把它编辑成这样:

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

它不再起作用了。输出将只是 "test: "。这不应该像这样工作还是我错过了什么?

提前致谢

你的问题是 OnMessage 是一个事件。 lambda 表达式 message => ... 在消息到达时执行。

// 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: "