Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

c# - what does a using statement without variable do when disposing?

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

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

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...