Hello Deepak !
Thank you for posting on Microsoft Learn.
The Azure IoT SDK for C# already supports retry policies, including exponential back-off, and you can apply them directly to your DeviceClient
instance.
Add the required namespaces :
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Retry;
Then, create the DeviceClient
with an ExponentialBackoff
RetryPolicy.
You need to instantiate the DeviceClient
with exponential back-off:
TimeSpan minBackoff = TimeSpan.FromSeconds(1);
TimeSpan maxBackoff = TimeSpan.FromSeconds(60);
TimeSpan deltaBackoff = TimeSpan.FromSeconds(5);
int maxRetryCount = 5;
RetryPolicy retryPolicy = new ExponentialBackoff(maxRetryCount, minBackoff, maxBackoff, deltaBackoff);
DeviceClient deviceClient = DeviceClient.CreateFromConnectionString("YourConnectionString", TransportType.Mqtt);
deviceClient.SetRetryPolicy(retryPolicy);
-
minBackoff
: Minimum backoff duration between retries
maxBackoff
: Maximum cap on the retry interval
deltaBackoff
: Added randomness (jitter)
maxRetryCount
: How many retries before giving up
You can monitor connection status (optional, for logging/debugging) :
deviceClient.SetConnectionStatusChangesHandler((status, reason) =>
{
Console.WriteLine($"Connection status: {status}, Reason: {reason}");
});
Now that retries are handled by the SDK using exponential back-off, your timer logic should check if the client is Connected
before doing work, and do nothing if it's retrying:
var status = deviceClient.GetConnectionStatus();
if (status == ConnectionStatus.Connected)
{
// Do your work
}
else
{
// Let the SDK handle retries; don't do anything here
Console.WriteLine("Device is retrying connection, skipping this cycle.");
}