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

前端 未结 4 1923
眼角桃花
眼角桃花 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.

提交回复
热议问题