简体   繁体   中英

Empty “using” block

It has already been determined here that an empty using block is not an appropriate way to override Dispose() , but what about the following case?

Is this a legitimate use for an empty using block?

try
{
    using (File.OpenRead(sourceFile)) { }
}
catch (FileNotFoundException)
{
    error = "File not found: " + sourceFile;
}
catch (UnauthorizedAccessException)
{
    error = "Not authorized to access file: " + sourceFile;
}
catch (Exception e)
{
    error = "Error while attempting to read file: " + sourceFile + ".\n\n" + e.Message;
}

if (error != null)
    return error;

System.Diagnostics.Process.Start(sourceFile);

No it's not a legitimate use for an empty using block.

You can simply write the try like this:

try
{
    File.OpenRead(sourceFile).Close();
}

Either OpenRead() will succeed and return a stream that you must close (or dispose, but I think .Close() better expresses your intent), or it will thrown an exception and not return anything.

Therefore you can always just close the returned value.

(I assume that you are just checking for read access before doing something else. However, be aware that you could in theory have a race condition because the accessibility of the file could change between you making this check and later on actually opening the file. This is unlikely to happen in practice, but you should be aware of the possibility.)

Not much sense in using empty using block, as you simply can add finally at the end of catch chains and handle Dispose there:

FileStream fs;
try {

    fs = File.OpenRead(sourceFile); 
}
catch(..) {
}
catch(..) {
}
catch(..) {
}
finally {

  if(fs !=null) {
      fs.Close();
      fs.Dispose();

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM