从Azure IoT中心获取设备列表 [英] Get a list of devices from Azure IoT Hub

查看:78
本文介绍了从Azure IoT中心获取设备列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Microsoft Azure IoT中心的新手.我想在IoT中心中获取设备列表,并检查列表中是否有任何设备.

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

}

但是,如果我在WebAPI中使用相同"代码,则GetDevicesAsync()会一直运行并没有任何结果.

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

我在做什么错了?

推荐答案

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

You can try with this code format:

...

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

...

对我有用.

有关更多信息,您可以参考初始文章"

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

由于这个问题, @Jason Malinowski的答案在一定程度上进行解释.

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

这篇关于从Azure IoT中心获取设备列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆