c# - 从 Azure IoT 中心获取设备列表

标签 c# azure asp.net-web-api azure-iot-hub

我是 Microsoft Azure IoT 中心的新员工。我想要获取 IoT 中心中的设备列表并检查列表中是否有任何设备。

如果我使用控制台应用程序,它可以正常工作。

static async void QueryDevices()
{
  registryManager = RegistryManager.CreateFromConnectionString(DeviceConnectionString);

  var devices = await registryManager.GetDevicesAsync(100); // Time 1 sek

  foreach (var item in devices)
  {
    Console.WriteLine("Divice id: " + item.Id + ", Connection state: " + item.ConnectionState);
  }
  Console.WriteLine("\nNumber of devices: " + devices.Count());

}

但是,如果我在 WebAPI 中使用“相同”代码,GetDevicesAsync() 会继续运行,但没有任何结果。

public bool CheckIoTHubConnection(string iotHubConnectionString)
{
  registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);

  return CreateConnection().Result;
}

private async Task<bool> CreateConnection()
{
  bool connectionOk = false;

  try
  {
    // Gets all devices from IoT Hub
    var result = await registryManager.GetDevicesAsync(10); // This never gets further

    if (result.Any())
      connectionOk = true;
  }
  catch (Exception ex)
  {
    connectionOk = false;
    throw ex;
  }

  return connectionOk;
}

我做错了什么?

最佳答案

您可以尝试使用以下代码格式:

...

System.Threading.ThreadPool.QueueUserWorkItem(a => CheckIoTHubConnection(iotHubConnStr));

...

这对我有用。

有关更多信息,您可以引用最初的帖子“Send to IoT hub from MVC Web API?”。

由于这个问题,@Jason Malinowski's answer可以在一定程度上解释。

关于c# - 从 Azure IoT 中心获取设备列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44563602/

相关文章:

azure - ARM 模板 Key Vault 引用中的“2019-09-01”

asp.net-mvc - 在 MVC API 中接受字节数组参数作为 Base64

json - 无法接受 XDomainRequest POST 到 WebAPI

c# - 如何使启动窗体最初不可见或隐藏

c# - 无法将源类型转换为目标类型

c# - 媒体基础: Writing G711 PCMU to mp4

c# - 如何在 Swagger 3 中按区域分隔 Controller ?

azure - 从 Azure 存档存储补充目录

Azure 事件目录 : Where is the MFA verified phone number stored?

c# - 获取 "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman