Get a list of devices from Azure IoT Hub

巧了我就是萌 提交于 2019-12-24 02:07:55

问题


I am new at Microsoft Azure IoT Hub. I want to get a list of devices in my IoT Hub and check if there are any devices in the list.

Its works fine if I use a console application.

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());

}

But if I use the "same" code in a WebAPI the GetDevicesAsync() keeps running and running without any result.

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;
}

What am I doing wrong?


回答1:


You can try with this code format:

...

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

...

It works for me.

For more information you can reference the initial post "Send to IoT hub from MVC Web API?".

And for the reason of this issue, @Jason Malinowski's answer may explains at a certain extent.



来源:https://stackoverflow.com/questions/44563602/get-a-list-of-devices-from-azure-iot-hub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!