c# - How to return an object that's dependent on a chain of using statements? -
i'd write method similar one:
c make() { using (var = new a()) using (var b = new b(a)) { return new c(b); } }
this bad since when method returns, c
keeps reference disposed object.
note that:
a
implementsidisposable
.b
implementsidisposable
.c
not implementidisposable
since author ofc
statedc
not take ownership ofb
.
your situation similar have seen when querying database. in attempt separate logic, see code this:
var reader = executesql("select ..."); while (reader.read()) // <-- fails, because connection closed. { // process row... } public sqldatareader executesql(string sql) { using (sqlconnection conn = new sqlconnection("...")) { conn.open(); using (sqlcommand cmd = new sqlcommand(sql, conn)) { return cmd.executereader(); } } }
but, of course, can't work, because time sqldatareader
returns executesql
method, connection closed (disposed).
so alternative above makes use of delegates achieve separation of concerns, still allowing code work properly:
executesql(reader => { // write code reads sqldatareader here. }); public void executesql(string sql, action<sqldatareader> processrow) { using (sqlconnection conn = new sqlconnection("...")) { conn.open(); using (sqlcommand cmd = new sqlcommand(sql, conn)) { using (sqldatareader reader = cmd.executereader()) { while (reader.read()) { processrow(reader); } } } } }
so, perhaps can try similar in case? this:
makeandprocess(c => { // write code uses c here. // work, because , b not disposed yet. }); public void makeandprocess(action<c> processc) { using (var = new a()) using (var b = new b(a)) { processc(new c(b)); } }
Comments
Post a Comment