C# Linq-to-Sql – Should DataContext be disposed using IDisposable

Unlike most types which implement IDisposable, DataContext doesn’t really need disposing – at least not in most cases. I asked Matt Warren about this design decision, and here was his response: There are a few reasons we implemented IDisposable: If application logic needs to hold onto an entity beyond when the DataContext is expected to … Read more

What is the difference between using and await using? And how can I decide which one to use?

Classic sync using Classic using calls the Dispose() method of an object implementing the IDisposable interface. using var disposable = new Disposable(); // Do Something… Is equivalent to IDisposable disposable = new Disposable(); try { // Do Something… } finally { disposable.Dispose(); } New async await using The new await using calls and await the … Read more

When should I use GC.SuppressFinalize()?

SuppressFinalize should only be called by a class that has a finalizer. It’s informing the Garbage Collector (GC) that this object was cleaned up fully. The recommended IDisposable pattern when you have a finalizer is: public class MyClass : IDisposable { private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!disposed) { … Read more

What is IDisposable for?

Garbage collection is for memory. You need to dispose of non-memory resources – file handles, sockets, GDI+ handles, database connections etc. That’s typically what underlies an IDisposable type, although the actual handle can be quite a long way down a chain of references. For example, you might Dispose an XmlWriter which disposes a StreamWriter it … Read more

What does Process.Dispose() actually do?

Do I really need to Dispose() every Process object and how do I decide if I need to do so? Yes, you should dispose them. Note this text in the documentation for Process: A system process is uniquely identified on the system by its process identifier. Like many Windows resources, a process is also identified … Read more

Implementing IDisposable on a subclass when the parent also implements IDisposable

When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else. This is something you shouldn’t be concerned with. When you subclass an IDisposable class, all of the “Dispose pattern” plumbing is already being … Read more