code_junkie

Since .NET has a garbage collector why do we need finalizers/destructors/dispose-pattern?

Nov 12th, 2011
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. public void Log(string line)
  2. {
  3. var sw = new StreamWriter(File.Open(
  4. "LogFile.log", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));
  5.  
  6. sw.WriteLine(line);
  7.  
  8. // Since we don't close the stream the FileStream finalizer will do that for
  9. // us but we don't know when that will be and until then the file is locked.
  10. }
  11.  
  12. public void Log(string line)
  13. {
  14. using (var sw = new StreamWriter(File.Open(
  15. "LogFile.log", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))) {
  16.  
  17. sw.WriteLine(line);
  18. }
  19.  
  20. // Since we use the using block (which conveniently calls Dispose() for us)
  21. // the file well be closed at this point.
  22. }
Add Comment
Please, Sign In to add comment