When do we need to call Dispose() in dot net c#?

前端 未结 4 1957
眼角桃花
眼角桃花 2020-12-10 05:58

Do I need to dispose a sqldatareader after it is created?

SqlDataReader reader;
---
---
---
reader.Close();
reader.Dispose();
4条回答
  •  忘掉有多难
    2020-12-10 06:16

    Rule of thumb: if a class implements IDisposable you should always call the Dispose method as soon as you have finished using this resource. Even better wrap it in a using statement to ensure that the Dispose method will be called even if an exception is thrown:

    using (var reader = conn.ExecuteReader())
    {
        ...
    }
    

提交回复
热议问题