Will putting a “using” statement around a DataReader close it?

后端 未结 4 1466
栀梦
栀梦 2020-12-18 17:52

I usually write my DataReader code like this:

try
{
    dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
    while (dr.Read())
    {
               


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-18 18:39

    From what I can recall, if an exception occurs in a Using block, then the Dispose method is still called on the object. I usually have a Using statement for all disposable objects, without a Try..Catch.

    EDIT: Forgot to say that for some objects, calling Dispose will in turn call Close for that object.

提交回复
热议问题