Sunday, June 30, 2013

why do we use using() when creating an object of IO stream?

Is it nessesary? No


It is highly recommended? Yes!


The Problem is that StreamWriter uses umanaged resources. Unamanged reousrces have to be freed. If you jsut stop referencing it, the GC will at some undertermined point in the Future (between now and end of appliaction) collect the Isntance and also free the Umanaged Resources. But "undertermined point in Future" is just too late. You need a way to explicitly give the unmanaged resources back.


Hence all Classes that use Unamanged Resources (should) also implement the iDisposable Interface. Calling iDisposable.Dispose() is a way to make certain that the unmanaged Resources are returned now. Dispose will also usually Close() the object, wich in turn includes Flush().


All using does is make certain Dispose() is called after the using block is left, even in case of an exception. It is identical to (and compiled as) try...finally block. And that is why the use of using is highly recommended, whenever you deal with unmanaged Resources (like Files and Network Connections).




Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2


No comments:

Post a Comment