我的理解是,SqlConnection(ADO.NET)是一个有管理的物体,因此我们如何处置?
The "managed" word here only refers to memory. So the memory used for the Sqlconnection
object is managed and will be released appropriately, but the network, file, special shared memory, or named pipe resources used for completing the connection are not managed, and need to be disposed properly.
事实上, 任何实施<代码>的可支配的>条令:
- Be wrapped in a
using
block
- Be wrapped in
try
/finally
blocks
- Be used as a member of a type that itself implements
IDisposable
.
Always
www.un.org/spanish/ga/president 只有在涉及未经管理的资源的情况下才能使用可支配的>代码。
As for the finally
block, in this case, yes, the finally
block is enough, and using
is not strictly required.
然而,<代码> 副渔获物/代码> 这里的封锁绝对毫无用处......更糟糕的是,它摧毁任何最终例外的号召。 换言之,仅仅删除<条码>副渔获物/代码>栏目,不仅安全,而且,如果你这样做,你可重新填上。
一旦这样做,你就可以节省更多的代码,同时完全更换<条码>、<>条码>和<条码>,定有条码>的区块,代之以<条码/条码>的新<条码>,从此可以节省另外两条线路和一层tation,代之以新的<条码>使用瓦尔代码>。
最后,<代码>sqlConn 以前使用<新SqlConnection的物体在首次申报时分配的<代码>,该物体被彻底涂.,这种变数是前所未有的。 因此,我们也能够清理。
要求它像这样:
public DataSet GetFacilitiesInfo(string userName = null)
{
DataSet Ds = new DataSet();
string storedProcName = "FacilitySelect";
DBConnection cn = new DBConnection();
using var sqlConn = cn.DBConnTIP(_connectionString);
using var sqlCommand = new SqlCommand(storedProcName, sqlConn);
using var sqlDa = new SqlDataAdapter(sqlCommand);
sqlDA.Fill(Ds);
return Ds;
}
This is safer (all the IDisposables are accounted for), has better error handling (call stack is preserved), uses noticeably less code (always a win), and with absolutely no loss of function.
就完整性而言,这里的版本也使用一些电离层,以利用<代码>用户Name<>> 代码。 论点:
public DataSet GetFacilitiesInfo(string userName = null)
{
DataSet Ds = new DataSet();
string storedProcName = "FacilitySelect";
DBConnection cn = new DBConnection();
using var sqlConn = cn.DBConnTIP(_connectionString);
using var sqlCommand = new SqlCommand(storedProcName, sqlConn);
using var sqlDa = new SqlDataAdapter(sqlCommand);
sqlCommand.CommandType = CommandType.StoredProcedure;
// I have to guess the type and length
sqlCommand.Parameters.Add("@UserName", SqlDbType.NVarchar, 25).Value = userName;
if (userName == null) sqlCommand.Parameters["@UserName"].Value = DBNull.Value;
sqlDA.Fill(Ds);
return Ds;
}
That said, it is somewhat common to want actual meaningful error handling in this type of method, with a real catch
block. And once you do that, you re back to where a finally
block is just as good.