Dispose object that has been instantiated as method parameter c#

后端 未结 2 1216
陌清茗
陌清茗 2021-01-18 20:51

I have the following classes:

private static readonly string ConnectionString = \"Dummy\";
public static SqlConnection GetConnection()
{
    SqlConnection Co         


        
2条回答
  •  感情败类
    2021-01-18 21:40

    No, the adapter does not dipose the connection. You should change it to this at least:

    public static SqlDataAdapter GetDataAdapter(SqlConnection connection, string Query)
    {
        SqlDataAdapter Adapt = new SqlDataAdapter(Query);
        Adapt.Connection = connection;
        return Adapt;
    }
    

    and use it like this

    using (var connection = GetConnection())
    using (var adapter = GetAdapter(connection, query))
    {
        // do stuff
    }
    

    This way you are also more flexible by being able to pass some other connection in - in case you need it for some exceptional circustances.

提交回复
热议问题