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

本文关键字:存储 变量 事件驱动的 消息 | 更新日期: 2023-09-27 17:53:51

我试图建立一个基本连接到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:"。这不应该是这样的吗,还是我错过了什么?

Thanks in advance

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

你的问题是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: "