Search code examples
c#filestreamusingtry-catch-finally

Stream management after Environment.exit() invocation


I was searching in StackOverflow about try-finally and using blocks and what are the best practices on using them. I read in a comment here that if your application is terminated abruptly by killing the process, a finally block will not get executed.

I was wondering, does the same apply to the using blocks? Will for example a stream get closed if a Environment.exit() call occurs inside the using block?:

//....
using (FileStream fsSource1 = new FileStream(pathSource,
        FileMode.Open, FileAccess.Read))
{
  //Use the stream here
  Environment.exit();
}

As a second thought on it, and knowing that CLR Garbage Collector will probably take care of the stream objects if not closed properly in the program calls, is it considered necessary to close a stream in code, if the program gets terminated for sure after the completion of the stream usage?

For example, is there any practical difference between:

//....
using (FileStream fsSource1 = new FileStream(pathSource,
        FileMode.Open, FileAccess.Read))
{
  //Use the stream here
}
Environment.exit();

And:

//....
FileStream fsSource1 = new FileStream(pathSource, FileMode.Open, FileAccess.Read);
//Use the stream here
Environment.exit();

Or even the example mentioned before?


Solution

  • It shouldn't make a difference in the specific case of FileStream, modulo a tricky corner case when you used its BeginWrite() method. Its finalizer attempts to complete writing any unwritten data still present in its internal buffer. This is however not generally true, it will make a difference if you use StreamWriter for example.

    What you are leaving up to the .NET Framework to decide is whether you truly meant to jerk the floor mat and seize writing the file. Or whether it should make a last-gasp attempt to flush any unwritten data. The outcome in the case of StreamWriter will tend to be an unpleasant one, non-zero odds that something is going to fall over when it tries to read a half-written file.

    Always be explicit, if you want to make sure this does not happen then it is up to you to ensure that you properly called the Close() or Dispose() method. Or delete the file.