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

C#: Do I need to dispose a BackgroundWorker created at runtime?

Yes, you should dispose of the background worker. You may find it easier to use ThreadPool.QueueUserWorkItem(…) which doesn’t require any clean up afterwards. Additional detail on why you should always call Dispose(): Although if you look in the BackgroundWorker class it doesn’t actually do any thread clean up in it’s dispose method, it is still … Read more

Is SqlCommand.Dispose() required if associated SqlConnection will be disposed?

Just do this: using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[“MyConn”].ConnectionString)) using(var command = connection.CreateCommand()) { command.CommandText = “…”; connection.Open(); command.ExecuteNonQuery(); } Not calling dispose on the command won’t do anything too bad. However, calling Dispose on it will suppress the call to the finalizer, making calling dispose a performance enhancement.

Will a using clause close this stream?

Yes, StreamReader.Dispose closes the underlying stream (for all public ways of creating one). However, there’s a nicer alternative: using (TextReader reader = File.OpenText(“file.txt”)) { } This has the added benefit that it opens the underlying stream with a hint to Windows that you’ll be accessing it sequentially. Here’s a test app which shows the first … Read more

How bad is it to not dispose() in Powershell?

This has been edited to include a safe, nonspecific answer. IN GENERAL: dispose everything, because Dispose is the .NET framework’s way to free up external resources (such as file handles, TCP ports, database connections, etc). Resources are not guaranteed to be released unless you call Dispose(). So beware. This is the general, non-SharePoint answer. SPECIFICALLY … Read more

Does the “using” keyword mean the object is disposed and GC’ed?

You’re talking about two very different things. The object will be disposed as soon as the using-block ends. That doesn’t say anything about when it is garbage collected. The only time heap memory is released is when a garbage collection occurs – which only happens under memory pressure (unless you use GC.Collect explicitly). Disposing an … Read more

tech