How to delete all devices from Azure IoT Hub using C#?

2.2k views Asked by At

I tried to delete devices using RemoveDeciceAsync method through a loop after retrieving all devices using GetDevicesAsync method. But this deletion process throws exception sometimes for some devices. Please note that the exception is not always thrown. How can I clear all the devices from IoT hub using .Net SDK? Here is the source code to delete device: Source code to delete devices

Here is the exception screenshot. Here is the image of the exception

3

There are 3 answers

1
shachar On

It's hard to help you without the error but instead of using a loop with RemoveDeviceAsync the SDK provides a batch remove with force remove option.

RemoveDevices2Async(IEnumerable, Boolean, CancellationToken);

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.devices.registrymanager

0
Farhan Ghumra On

Try this

var registryManager = RegistryManager.CreateFromConnectionString(iot_hub_connectionString);

var deviceTwins = new List<Twin>();
var query = registryManager.CreateQuery("SELECT * FROM devices", int.MaxValue);
while (query.HasMoreResults)
{
    var page = await query.GetNextAsTwinAsync();
    deviceTwins.AddRange(page);
}

var devicesToDelete = deviceTwins.Select(t => { return new Device(t.DeviceId); });
var opResult = await registryManager.RemoveDevices2Async(devicesToDelete);
0
Olivier Bloch On

As mentioned by @Shachar, you need to use the RemoveDevices2Async API. In order to guarantee the service availability, IoT Hub throttles the number of operations for each compute unit. You can see here that the CRUD operations are throttled beyond 100/min. The RemoveDevices2Async API removes devices in bulk and one call counts for one operation only.