Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have to take care of Garbage collection in azure function?

I am using blob and queue storage,redis chache, documentdb and azure sql databases and creating CloudStorageAccount, client and container objects. Do these classes implements IDisposable. do I have to use "using" or try finally block to release the object/set it to null?

like image 422
Annie Avatar asked Feb 23 '18 10:02

Annie


1 Answers

Unfortunately it is not a straight answer. Some do implement IDisposable, some don't. In general .net practice, you should always dispose disposable objects, either in a finally or by using the using pattern. This is regardless of whether you are coding an Azure function, WebApp or console application, etc. You should not need to set objects to null, disposing is sufficient. Only un-managed objects need to be "nulled" and this will be done in the Dispose() method that is called. See the IDisposable pattern.

However, it is not that straight forward. for example, the CosmosDB connection implements IDisposable BUT the recommendation is to create a single instance / singleton to use for your application since the client is thread safe and multiple client instances can cause thread exhaustion in multi-threaded implementations, so you would not want each use wrapped in a using clause. Disposing becomes less important because the object's lifespan is the same (or close to) that of the App domain.

So, rule of thumb is always dispose, however, check the docs for best practice, especially when it comes to connection objects.

@McGuireV10 makes a good point and recommendation in the comments. You need to be aware that many instances of a function may execute within the same instance of the hosting app domain. Each function is an instantiation, not a new app domain (which happens periodically as the functions scale / move / change health)

like image 186
Murray Foxcroft Avatar answered Nov 03 '22 20:11

Murray Foxcroft