C# using 语句是否执行 try/finally ?

发布于 2024-08-30 01:59:34 字数 815 浏览 8 评论 0原文

假设我有以下代码:

private void UpdateDB(QuoteDataSet dataSet, Strint tableName)
{
    using(SQLiteConnection conn = new SQLiteConnection(_connectionString))
    {
        conn.Open();
        using (SQLiteTransaction transaction = conn.BeginTransaction())
        {
            using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tableName, conn))
            {
                using (SQLiteDataAdapter sqliteAdapter = new SQLiteDataAdapter())
                {
                    sqliteAdapter.Update(dataSet, tableName);
                }
            }
            transaction.Commit();
        }
    }
}

C# 文档指出,使用 using 语句,作用域内的对象将被释放,并且我看到了几个建议我们不需要使用的地方try/finally 子句。

我通常用 try/finally 包围我的连接,并且总是在 finally 子句中关闭连接。根据上面的代码,假设出现异常时连接将被关闭是否合理?

Suppose that I have the following code:

private void UpdateDB(QuoteDataSet dataSet, Strint tableName)
{
    using(SQLiteConnection conn = new SQLiteConnection(_connectionString))
    {
        conn.Open();
        using (SQLiteTransaction transaction = conn.BeginTransaction())
        {
            using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tableName, conn))
            {
                using (SQLiteDataAdapter sqliteAdapter = new SQLiteDataAdapter())
                {
                    sqliteAdapter.Update(dataSet, tableName);
                }
            }
            transaction.Commit();
        }
    }
}

The C# documentation states that with a using statement the object within the scope will be disposed and I've seen several places where it's suggested that we don't need to use try/finally clause.

I usually surround my connections with a try/finally, and I always close the connection in the finally clause. Given the above code, is it reasonable to assume that the connection will be closed if there is an exception?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

温折酒 2024-09-06 01:59:34

您是对的; using 语句编译为 try / finally

编译器将 using(resource) 语句; 转换为以下代码:(

{
   ResourceType resource = expression;
   try {
      statement;
   }
   finally {
      if (resource != null) ((IDisposable)resource).Dispose();
   }
}

如果 ResourceType 实现 IDisposable<,则转换为 IDisposable /code> 明确地。

You are correct; the using statement compiles to a try / finally block.

The compiler transforms using(resource) statement; into the following code:

{
   ResourceType resource = expression;
   try {
      statement;
   }
   finally {
      if (resource != null) ((IDisposable)resource).Dispose();
   }
}

(The cast to IDisposable is in case ResourceType implements IDisposable explicitly.

轻许诺言 2024-09-06 01:59:34

是的,您需要使用 try/finally 或 using 语句。你不需要两者。

using 语句 几乎是与 try/finally 相同,只是在 C# 3 中不能重新分配给 using 块内的变量。

using (IDisposable d = foo())
{
     d = null; // Error:  Cannot assign to 'd' because it is a 'using variable'
}

以前,您可以重新分配,但原始对象仍然会被释放,而不是新分配的对象,并且您还会收到此编译警告:

可能对本地“d”的赋值不正确,该“d”是 using 或 lock 语句的参数。 Dispose 调用或解锁将发生在本地的原始值上。

Yes, you either need to use a try/finally or a using statement. You don't need both.

A using statement is almost the same as a try/finally except that in C# 3 you can't reassign to the variable inside the using block.

using (IDisposable d = foo())
{
     d = null; // Error:  Cannot assign to 'd' because it is a 'using variable'
}

Previously you could reassign but the original object would still be disposed, not the newly assigned object and you would also get this compile warning:

Possibly incorrect assignment to local 'd' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.

云仙小弟 2024-09-06 01:59:34

是的,using 语句几乎只是 try ...finally 块的简写。

例如,这段代码...

using (MyDisposableType foo = new MyDisposableType())
{
    foo.DoSomething();
}

...相当于以下内容...

{
    MyDisposableType foo = new MyDisposableType();
    try
    {
        foo.DoSomething();
    }
    finally
    {
        if (foo != null)
            ((IDisposable)foo).Dispose();
    }
}

Yes, the using statement is pretty much just shorthand for a try ... finally block.

For example, this code...

using (MyDisposableType foo = new MyDisposableType())
{
    foo.DoSomething();
}

...would equate to the following...

{
    MyDisposableType foo = new MyDisposableType();
    try
    {
        foo.DoSomething();
    }
    finally
    {
        if (foo != null)
            ((IDisposable)foo).Dispose();
    }
}
左岸枫 2024-09-06 01:59:34

您可以假设如果出现异常,连接将被关闭。

You can assume that the connection will be closed if you get an exception.

人心善变 2024-09-06 01:59:34

using() 确保参数中实例化的项将被处理,无论关联代码块中发生什么情况。这包括关闭数据库连接(假设 SQLiteConnection 正确处理其处置)。

Using() ensures that the item instantiated within the parameters will be disposed of regardless of that happens within the associated code block. This includes closing the database connection assuming that SQLiteConnection handles its disposal correctly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文