Who Disposes of an IDisposable public property?

There is no single answer, it depends on your scenario, and the key point is ownership of the disposable resource represented by the property, as Jon Skeet points out. It’s sometimes helpful to look at examples from the .NET Framework. Here are three examples that behave differently: Container always disposes. System.IO.StreamReader exposes a disposable property … Read more

What’s the purpose of GC.SuppressFinalize(this) in Dispose() method?

When implementing the dispose pattern you might also add a finalizer to your class that calls Dispose(). This is to make sure that Dispose() always gets called, even if a client forgets to call it. To prevent the dispose method from running twice (in case the object already has been disposed) you add GC.SuppressFinalize(this);. The … Read more

Do I need to Dispose a SemaphoreSlim?

If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources. If you do not access AvailableWaitHandle, then No, calling Dispose() won’t do anything important. SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be useful, for example if you need to wait on multiple … Read more

Should HttpClient instances created by HttpClientFactory be disposed?

Calling the Dispose method is not required but you can still call it if you need for some reasons. Proof: HttpClient and lifetime management Disposal of the client isn’t required. Disposal cancels outgoing requests and guarantees the given HttpClient instance can’t be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances. … Read more

When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

So it seems like the calling code needs to know about and take ownership of the response message as well as the stream, or I leave the response message undisposed and let the finalizer deal with it. Neither option feels right. In this specific case, there are no finalizers. Neither HttpResponseMessage or HttpRequestMessage implement a … Read more

Manually destroy C# objects

You don’t manually destroy .Net objects. That’s what being a managed environment is all about. In fact, if the object is actually reachable, meaning you have a reference you can use to tell the GC which object you want to destroy, collecting that object will be impossible. The GC will never collect any object that’s … Read more