2

我想不断检查 azure servicebus/iothub 是否有消息。但是,当我这样做时,我收到以下错误

“在 mscorlib.dll 中发生了‘Amqp.AmqpException’类型的异常,但未在用户代码中处理附加信息:操作‘接收’在状态下无效:结束。”

有什么想法我应该如何实现不断提取消息和/或解决此错误?

var connection = new Connection(address);
var session = new Session(connection);
var entity = Fx.Format("/devices/{0}/messages/deviceBound", _deviceId);

var receiveLink = new ReceiverLink(session, "receive-link", entity);
while (true)
{
    await Task.Delay(1000);

    var message = await receiveLink.ReceiveAsync();
    if (message == null) continue;
    //else do things with message
 }
4

1 回答 1

0

从您使用的端点看来,您正在谈论接收云到设备 (c2d) 消息,换句话说,您编写的代码在设备上运行,旨在接收通过服务于这个设备,对吧?

最简单的方法是使用C# SDK的DeviceClient类。DeviceClientAmqpSample项目中提供了如何使用此类的示例。

使用设备连接字符串创建DeviceClient实例后,DeviceClient该类具有ReceiveAsync可用于接收消息的方法。

var deviceClient = DeviceClient.CreateFromConnectionString("<DeviceConnectionString>");
while(true)
{
    await Task.Delay(1000);
    var receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));
    if (receivedMessage != null)
    {
        var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
        Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
        await deviceClient.CompleteAsync(receivedMessage);
    }
}
于 2016-04-07T20:33:12.380 回答