c# - Disposing a data reader when constructing it by value vs reference -
rookie question when data reader gets released when it’s constructed in class using ref
vs. var. i’ve been testing today , results puzzling me bit – hoping clear in head.
i have class use fetching data via odbc numerous remote servers need restrict how many odbc connections open each server i'm attached – i’m being careful disposing data readers when i’m done them before opening another. short version have method called filldatareader
takes data reader object, , fills based on query , passes back.
if pass using ref
, dispose data reader calling side, well. connection released , client side can data reader filled without burning connection. if pass value, resource not released , if open data reader client side have 2 connections server.
conceptually difference – ref
single address being used it’s passing “pointer pointer” , dispose releases resource. ok, if passing value , doing explicit dispose on client side what, exactly, holding resource? i’d rather pass value here can use nifty using
construct on client side more importantly want understand better what’s happening here. in nutshell here’s looks like
[db fetch class]
public bool filldatareader(string pquerystring, ref system.data.odbc.odbcdatareader pdatareader, out string perrorreason) { (uses connection object that’s been established @ class construction time , stays time) ... try { pdatareader = _command.executereader(); } ... } [calling class] strsql = "select alias, objectid, vw_globaluser"; if (serverlist[currentserver].databasefunctions.filldatareader(strsql, ref drtemp, false, out strerrorreason) == false) …. drtemp.dispose(); (at point connection released server)
however if take ref
out @ point of dispose in calling class connection not released. goes away need gone (hence call dispose).
so fill function in db fetch class hanging onto reference allocated space on heap somehow? i’m not sure understand why – understood it’s using copy of address data reader on stack reference data reader object on heap there when goes out of scope, isn’t released? maybe need more coffee…
since calling code needs receive reference release object, need ref
(or out
). otherwise parameter passed method, not back, drtemp
isn't updated data reader created in filldatareader
method.
note may want change signature follows make intention more clear:
public result trygetdatareader(string pquerystring, out system.data.odbc.odbcdatareader pdatareader)
changes propose:
- introduced naming convention "try", common type of method
- made pdatareader
out
, since doesn't need initialized when calling method - introduced "result" type, should carry success information , error message (if any)
Comments
Post a Comment