When to close connection?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a function that returns a SqlDataReader created by:

result = command.ExecuteReader(CommandBehavior.CloseConnection);

I then bind the result to a grid control:

myDataGrid.DataSource = sr;
myDataGrid.DataBind();

Do I need to explicitly close the DataReader (and thus the connection) after
the DataBind?

Thanks,
Bill
 
your function should use sqlreader.close. That should also take care of the
connection but I see your CommandBehavior is also taking care of the closing
the connection . In the calling client user sr = nothing.
 
If I do:

sr = null;

Won't this just flag the object for deletion until the garbage collection
actually destroys it? If I need to explicity close the reader, would it not
be better to call the Close method?

Anyhow, so I guess you are saying by this that I could also wait until the
Grid goes out of scope which will also set the sr to null.

Thanks
Bill
 
This is a sample

Try

DR = db.ExecuteReader(whatever)

While DR.Read

MsgBox(DR.Item(0))

End While

Catch ex As Exception

MsgBox(ex.Message)

Finally

If (Not DR Is Nothing) Then
DR.Close()
End If

End Try

look at the finally block and convert to c#.
 
Bill,

sr = null; or sr = nothing does in my opinion absolute nothing here, when
your page is sent back, everything that is not shared will be completely
released by the GC at the right time.

Clossing a connection is always needed of the connection pooling.
(Which you did as Chris already wrote)

I hope this gives an idea

Cor
 
Back
Top