static void tryDispose() { PersonDisposable p = null; var y = 0; try { p = new PersonDisposable { Name = "Kate" }; var x = 10 / y; } finally { if (p != null) { p.Dispose(); } } }
public static void Display() { Test(); GC.Collect(); PersonDisposable p2 = new PersonDisposable { Name = "Bob" }; p2.Dispose(); try { tryDispose(); } catch { } using (PersonDisposable p = new PersonDisposable()) { p.Name = "Jane"; } }
// An object can implement the IDisposable interface, which means it must provide a Dispose method that can be called within // the application to request that the object to release any resources that it has allocated. Note that the Dispose method // does not cause the object to be deleted from memory, nor does it mark the object for deletion by the garbage collector // in any way. Only objects that have no references to them are deleted. Once Dispose has been called on an object, // that object can no longer be used in an application. Objects that implement IDisposable can be used in conjunction with // the using statement, which will provide an automatic call of the Dispose method when execution leaves the block that // follows the using statement. The Dispose method is called by the application when an object is required to release all the // resources that it is using. This is a significant improvement on a finalizer, in that your application can control // exactly when this happens. // If you want to create an object that contains both a finalizer and a Dispose method you need to exercise // some care to avoid the object trying to release the same resource more than once, and perhaps failing as a // result of this. The SuppressFinalize method can be used to identify an object, which will not be finalized // when the object is deleted. This should be used by the Dispose method in a class to prevent instances being // disposed more than once. A dispose pattern can be used to allow an object to manage its disposal. public void TheDisposaPattern() { PersonDisposable personDisposable = new PersonDisposable(); personDisposable.Dispose(); }