问题
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