Object references are lost but the resources held

2020-03-27 10:43发布

IndentedTextWriter tw = new IndentedTextWriter(internalTW, "    ");

Object referenced by 'tw' is lost, but related resources are not disposed here "TW " is a text writer where internalTW is a TextWriter

 OleDbConnection con = new OleDbConnection(conStr);
 OleDbCommand cmd = new OleDbCommand(cmd1, con);

object referenced by 'cmd' is lost, but related resources are not disposed here

标签: c#
2条回答
家丑人穷心不美
2楼-- · 2020-03-27 11:23

Try

using (IndentedTextWriter tw = new IndentedTextWriter(internalTW, "    ")) {
  // use it here
}

resp.

using (OleDbConnection con = new OleDbConnection(conStr))
using (OleDbCommand cmd = new OleDbCommand(cmd1, con)) {
  // use it here
}

At the end of the using block, Dispose() is called on the objects and the resources should be freed...

查看更多
太酷不给撩
3楼-- · 2020-03-27 11:33

The types all implement IDisposable, and thus it is the caller's responsibility to call Dispose() like e.g.

using(var tw = new IndentedTextWriter(internalTW, "    ")) {
    // do something with tw
}

or by explicitly calling Dispose() in a finally block.

查看更多
登录 后发表回答