Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we need to call Dispose() in dot net c#?

Tags:

c#

.net

dispose

Do I need to dispose a sqldatareader after it is created?

SqlDataReader reader;
---
---
---
reader.Close();
reader.Dispose();
like image 221
Paras Avatar asked May 05 '11 10:05

Paras


People also ask

Do you need to call Dispose?

If you are using a class that implements the IDisposable interface, you should call its Dispose implementation when you are finished using the class.

When the Dispose method is called?

It only occurs when there are objects in the Finalization Queue. It only occurs when a garbage collection occurs for Gen2 (which is approx 1 in every 100 collections for a well-written . NET app).

When we use Dispose in C#?

The dispose pattern is used for objects that implement the IDisposable interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects.

Do you need to Dispose task C#?

“No. Don't bother disposing of your tasks, not unless performance or scalability testing reveals that you need to dispose of them based on your usage patterns in order to meet your performance goals.


1 Answers

Rule of thumb: if a class implements IDisposable you should always call the Dispose method as soon as you have finished using this resource. Even better wrap it in a using statement to ensure that the Dispose method will be called even if an exception is thrown:

using (var reader = conn.ExecuteReader())
{
    ...
}
like image 69
Darin Dimitrov Avatar answered Sep 17 '22 19:09

Darin Dimitrov