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

时间:2016-06-30 12:11:50

标签: c# azure servicebus

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

一个有效的例子:

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

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

提前致谢

1 个答案:

答案 0 :(得分:1)

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