Disposables, Using & Try/Catch Blocks

时间秒杀一切 提交于 2019-11-29 10:32:31

You're just being paranoid and it will work the way you intend it to :)

A using statement is equivalent to a try/finally block, whether it's inside a try/catch or not.

So your code is similar to:

try
{
   FileStream fs = null;
   try
   {
       fs = File.Open("Foo.txt", FileMode.Open);
       // Do stuff
   }
   finally
   {
       if (fs != null)
       {
           fs.Dispose();
       }
   }
}
catch(Exception)
{
   /// Handle Stuff
}

Don't worry, it will clean up as expected and is cleaner than your original.

In fact it's much more common to have a try/finally aka using statement in your business logic, and a try/catch in a top-level handler in the UI tier or at a physical tier boundary. Something like:

try
{
    DoStuffWithFile("foo.txt");
}
catch(Exception ex)
{
   ...
}

and

public void DoStuffWithFile(string fileName)
{
    using(FileStream fs = File.Open(fileName,...))
    {
        // Do Stuff
    }
}

This will work - internally the using statement compiles the same way as a try-finally block

    try
    {
        FileStream fs = null;
        try
        {
           fs = File.Open("Foo.txt", FileMode.Open);

        }
        finally
        {
           fs.Dispose();
        }
    }
    catch(Exception)
    {
       /// Handle Stuff
    }

second piece of code gets translated into this

The using block will work exactly as you entend translated the using block is really just

try
{
   FileStream fs = null;
   try
   {
        fs = File.Open("Foo.txt", FileMode.Open))
        //Do Stuff
   }
   finally
   {
      if(fs != null)
          fs.Dispose();
   }
}
catch(Exception)
{
   /// Handle Stuff
}

You don't need the try..finally if you have a using(). They perform the same operation.

If you're not convinced, point Reflector at your assembly and compare the generated code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!