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

前端 未结 4 1920
眼角桃花
眼角桃花 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:02

    It is recommended to use the using pattern when dealing with anything that implements IDisposable

    using ()
    {
        // use it here
    }
    

    This will look after the try..catch..finally construct and calling Dispose.

    EDIT I had previously said that I thought Close and Dispose did the same thing for readers (stream, file, sqldatareader etc.) but it appears this is not true looking at the documentation on SQLDataReader so my assumption was wrong.

    0 讨论(0)
  • 2020-12-10 06:14

    There is a simple guideline: if you have finished with an object whose type implements IDisposable then call Dispose() on it; you should use a using block to do this.

    0 讨论(0)
  • 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())
    {
        ...
    }
    
    0 讨论(0)
  • 2020-12-10 06:16

    Object which are Disposable can be best used (if possible) in a using block. At the end of the using block, the object is automatically disposed.

    Because of memory management it is always advised do dispose your objects if you don't need them anymore.

    Here's some stuff to read from the MSDN.

    0 讨论(0)
提交回复
热议问题