Which is better, and when: using statement or calling Dispose() on an IDisposable in C#?

落花浮王杯 提交于 2019-12-18 06:13:03

问题


Suppose I have the following:

using(var ctx = DataContextFactory.Create(0))
{ ... Some code ... }

Why not just do the following and lose a couple of curly braces?:

var ctx = DataContextFactory.Create(0);
ctx.Dispose();

Thanks for the advice!


回答1:


The first is better. It ensures it is disposed even if an exception is thrown, and it correctly handles the case where Create(0) returns null (i.e. it doesn't attempt to call Dispose() on a null instance).




回答2:


A using statement is always better because...

  • you can't forget to call Dispose(), even as the code evolves into different code paths
  • Dispose() gets called even if there's an exception. It also checks for null before calling Dispose(), which may be useful (assuming you're not just calling new).

One non-obvious (to me, anyway) trick with using is how you can avoid excessive nesting when you have multiple disposable objects:

using (var input = new InputFile(inputName))
using (var output = new OutputFile(outputName))
{
    input.copyTo(output);
}

The VS code formatter will leave the two statements starting in the same column.


In fact, in some situations you don't even have to repeat the using statement...

using (InputFile input1 = new InputFile(inputName1), input2 = new InputFile(inputName2))

However, the restrictions for declaring multiple variables on the same line applies here so the types must be the same and you cannot use the implicit type var.




回答3:


Where you can, use using for the reasons Marc cites. OTOH this isn't a brain dead solution as sometimes the lifetime of the object can't be defined as a lexical scope so use it reasonably.




回答4:


The only place you don't want to use a using block is where the disposable object is scoped outside of the function. In this case, your class should implement IDisposable and dispose of the object in its Dispose().




回答5:


The using statement gives you nice syntax plus exception protection. You cannot leave the using statement without calling Dispose (it translates into a finally block with a call to dispose). In your second scenario, if you had an exception between the Create and the Dispose, you would not call dispose directly. Which is not a problem unless you are using unmanaged resources, but if you are, you will leak.



来源:https://stackoverflow.com/questions/1034639/which-is-better-and-when-using-statement-or-calling-dispose-on-an-idisposabl

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