3

Microsoft.Azure.Devices.ServiceClient and Microsoft.Azure.Devices.RegistryManager both have ConnectFromConnectionString and CloseAsync methods.

Should we use them like we use other .NET connection-close patterns, such as ADO.NET connections, Redis connections, Sockets' etc.? When I use objects like those I try to Close or Disposable.Dispose() of them as soon as possible.

What's the upside and downside to doing the same with the Microsoft.Azure.Devices objects when accessing the same IOT Hub? I have running code that treats the individual RegistryManager and ServiceClient instances as singletons, which are used throughout an application's lifetime -- which may be weeks or months. Are we short circuiting ourselves by keeping these objects "open" for this duration?

Howard Hoffman
  • 897
  • 1
  • 9
  • 22
  • Close and reopen will cost some time if it is not a problem for you, close them when they are will not be used for a long time and reopen when it is needed. – Rita Han Aug 10 '17 at 06:55
  • 3
    Rita - or anyone - can you confirm that keeping the connections open for weeks or months won't itself lead to a memory or other leak that will destabilize our application? Does anyone have any data on how-fast or slow re-opening the connections would be? Is closing/re-opening actually an anti-pattern? – Howard Hoffman Aug 14 '17 at 15:46

2 Answers2

1

As pointed by @David R. Williamson, and this discussion on GitHub, it is generally recommended to register RegistryManager and ServiceClient as singletons.

For ASP NET Core or Azure Functions, it can be done as follows at startup:

ConfigureServices(services)
{
  services.AddSingleton<RegistryManager>(RegistryManager.CreateFromConnectionString("connectionstring"));
}
Dilpreet
  • 37
  • 1
  • 6
0

I'm on the Azure IoT SDK team. We recommend keeping the service client instances around, depending on your usage pattern.

While it is generally fine to init/close/dispose the Azure IoT service clients, you can run into the HttpClient socket exhaustion problem. We've done work to prevent it from happening if you keep a singleton of the client around, but when the client is disposed 2 HttpClient instances are also disposed.

There's little harm in keeping them around and will save your program execution time in init/dispose.

We're working on a v2 where we'll allow the user to pass in their own copy of HttpClient, so you could keep that around and shut down our client more frequently.