Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've always used using with variable and assignment. Now i have like this a class DbProviderConnection:

public class DbProviderConnection : IDisposable
{
    public DbConnection Connection { get; set; }
    public DbTransaction Transaction { get; set; }

    public DbTransaction BeginTransaction()
    {
        Transaction = Connection.BeginTransaction();
        return Transaction;
    } 

    //... and so on
}

Now i was thinkin to use it like this:

using (DbProviderConnection cnctn = _planDb.CreateOpenConnection())
{
    using (cnctn.BeginTransaction())
    {
        //...
        cnctn.Transaction.Commit();
    }
}

My question is: Is the DbProviderConnection.Transaction.Dispose called?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
399 views
Welcome To Ask or Share your Answers For Others

1 Answer

From C# Specification 8.13 using statement defined as

using-statement:
   using (resource-acquisition) embedded-statement

Where resource-acquisition is

resource-acquisition:
    local-variable-declaration
    expression

In first case you have using which acquires resource via local variable declaration. In second case resource is acquired via expression. So, in second case resouce will be result of cnctn.BeginTransaction() call, which is DbTransaction from your DbProviderConnection class. Using statement disposes its resource after usage. So, yes, DbProviderConnection.Transaction.Dispose() will be called.

UPDATE: According to same article, your second using block will be translated to

DbTransaction resource = cnctn.BeginTransaction();
try
{
    //...
    cnctn.Transaction.Commit();
}
finally 
{
   if (resource != null) 
      ((IDisposable)resource).Dispose();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...