9

If I have a using block surrounding a try catch statement what will happen to the object inside that using statement should the catch fire an exception? Consider the following code:

using (IDatabaseConnectivityObject databaseConnectivityObject = new DbProviderFactoryConnectionBasicResponse())
{
    try
    {
        Foo();
    }
    catch (ArgumentNullException e)
    {
        throw;
    }
}

If we assume Foo() fails and the exception is fired and effectively breaks the program will databaseConnectivityObject be disposed? The reason this is important is that the object has a database connection associated with it.

4

5 回答 5

12

您可以将其using视为 try-finally 的简写。因此,您的代码相当于:

IDatabaseConnectivityObject databaseConnectivityObject = new DbProviderFactoryConnectionBasicResponse();
try
{
    try
    {
        Foo();
    }
    catch(ArgumentNullException e)
    {
        throw;
    }
}
finally
{
  if(databaseConnectivityObject != null)//this test is often optimised away
    databaseConnectivityObject.Dispose()
}

这样看,你可以看到Dispose()如果抛出异常,确实会调用 ,因为 try-finally 在 try-catch 之外。

这正是我们使用using.

于 2012-09-03T10:25:25.030 回答
7

we assume Foo() fails and the exception is fired and effectively breaks the program will databaseConnectivityObject be disposed?

Yes it will be. using internally uses try-finally, (using only works for those which implements IDisposable)

From MSDN- using statement

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

于 2012-09-03T10:22:20.697 回答
3

是的using,无论您是否有 try-catch 块,您的块都会处理 databaseConnectivityObject。

您正确地说 using 块很重要,您应该将它用于所有实现的类,IDisposable以确保即使在发生异常时也能正确处理它们。

来自MSDN- using 声明

using 语句可确保调用 Dispose,即使在调用对象上的方法时发生异常也是如此。您可以通过将对象放在 try 块中,然后在 finally 块中调用 Dispose 来获得相同的结果;事实上,这就是编译器翻译 using 语句的方式。

于 2012-09-03T10:23:51.910 回答
3

在实现块时,如果它实现了接口using,括号中的对象将被释放。IDisposable

即使foo()失败,它仍然会被处理掉。

using 语句中的对象必须实现该IDisposable接口。

此外,这些问题“Uses of using in c sharp”“using statement vs try finally”using进一步说明了该语句的用途和实用性。

C# 语言规范的第 8.13 节清楚地详细说明了 using 语句。

于 2012-09-03T10:24:01.730 回答
2

您的using 代码相当于

IDatabaseConnectivityObject databaseConnectivityObject = new IDatabaseConnectivityObject ();
try
{
//To do code here
}
finally
{
    if(databaseConnectivityObject!=null)
    {
       databaseConnectivityObject.Dispose();
    }
}

使用语句主要分为三部分,即

  1. 获得
  2. 用法
  3. 处理

首先,通过 finally 语句获取资源并在 try 块上进行使用。最后,将对象放置在 finally 块中,如上面等效代码中给出的......

于 2012-09-03T10:26:49.160 回答