【问题标题】:If I return a value inside a using block in a method, does the using dispose of the object before the return?如果我在方法的 using 块内返回一个值,那么 using 在返回之前会处理该对象吗?
【发布时间】:2010-02-22 18:37:36
【问题描述】:

我正在查看 ASP.NET 应用程序中的一些旧 C#.NET 代码,以确保所有 SqlConnections 都包装在 using 块中。

我知道 usingtry / finally 相同,它在 finally 中处理对象> 不管try中发生了什么。如果我有一个在 using 中返回值的方法,即使执行在返回时离开该方法,它是否仍然在我的对象上调用 .Dispose()/在它返回期间/之后?

public static SqlCommand getSqlCommand(string strSql, string strConnect){
    using (SqlConnection con = new SqlConnection(strConnect))
    {
        con.Open();
        SqlCommand cmd = GetSqlCommand();
        cmd.Connection = con;
        cmd.CommandText = strSql;
        return cmd;
    }
}

更新: 接受的答案是我认为最能回答我的问题的答案,但请注意 this answer 发现了这段代码的愚蠢之处,即我正在返回一个使用已处置连接的命令! :P

【问题讨论】:

    标签: c# .net idisposable


    【解决方案1】:

    是的。它会处理你的对象。这实际上会导致您的代码出现问题,因为返回的SqlCommand 取决于SqlConnection,它将在控制流返回给您的调用者之前被处理掉。

    但是,您可以使用委托来解决此问题。处理这个问题的一个很好的模式是像这样重写你的方法:

    public static SqlCommand ProcessSqlCommand(string strSql, string strConnect, Action<SqlCommand> processingMethod)
    { 
        using (SqlConnection con = new SqlConnection(strConnect)) 
        { 
            con.Open(); 
            SqlCommand cmd = GetSqlCommand(); 
            cmd.Connection = con; 
            cmd.CommandText = strSql; 
            processingMethod(cmd); 
        } 
    } 
    

    你可以这样称呼它:

    ProcessSqlCommand(sqlStr, connectStr, (cmd) =>
        {
            // Process the cmd results here...
        });
    

    【讨论】:

    • 哇,好收获!谢谢。这种方法在很多地方都没有使用(而且很旧),所以我可能会删除它并在我需要的地方创建命令
    【解决方案2】:

    是的,它仍然会调用 dispose。

    运行这个非常简单的控制台应用程序顶部验证:

       class Program
        {
            static void Main(string[] args)
            {
                TestMethod();
                Console.ReadLine();
            }
    
            static string TestMethod()
            {
                using (new Me())
                {
                    return "Yes";
                }
            }
        }
    
        class Me : IDisposable
        {
            #region IDisposable Members
    
            public void Dispose()
            {
                Console.WriteLine("Disposed");
            }
    
            #endregion
        }
    

    【讨论】:

      猜你喜欢
      • 2011-09-15
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多