microsoft / PowerPlatform-DataverseServiceClient

Code Replica for Microsoft.PowerPlatform.Dataverse.Client and supporting nuget packages.
MIT License
285 stars 52 forks source link

Memory leak caused by exception thrown when constructing ServiceClient #322

Closed zhaohangChen closed 2 years ago

zhaohangChen commented 2 years ago

Hi team, We observe there is memory leak when our sevice is using Microsoft.PowerPlatform.Dataverse.Client.ServiceClient. When we call the constructor of Microsoft.PowerPlatform.Dataverse.Client.ServiceClient, if it throws exception, its member DataverseTraceLogger which is Disposable won't be disposed. That cause a sever memory leak in our service when it runs for some time.

Can we enhance the logic or provide some guaidance to avoid this? It's hard for our service to prevent the exception before invoking the ctor(). Also when the exception is thrown, even if we catch it, we can't dispose the object since no reference would be returned.

zhaohangChen commented 2 years ago

As discussed internally with @MattB-msft, there is a workaround for this problem: Use the Connection Settings Constructor with deferred activation instead of the Constructor which do the activation inside and lead to the memory leak issue. An example of changed code: image By this the invoker can obtain the reference to ServiceClient before exception is thrown during activation. Thus dispose() can be called to prevent the leak.

MattB-msft commented 2 years ago

We have a fix queued for this which will be in the next drop.