如果我有以下內容,仍然會在DisposeableObject上調用IDisposeable,還是會因爲遇到未處理的異常而保持打開對象?IDisposeable在使用語句中遇到未處理的異常時調用嗎?
using (DisposeableObject = new Object())
{
throw new Exception("test");
}
如果我有以下內容,仍然會在DisposeableObject上調用IDisposeable,還是會因爲遇到未處理的異常而保持打開對象?IDisposeable在使用語句中遇到未處理的異常時調用嗎?
using (DisposeableObject = new Object())
{
throw new Exception("test");
}
根據MSDN,yes。當控制權離開using
聲明的範圍時,期望將其處置。
該對象將被放置,因爲當異常冒泡時您將超出範圍。
請參見:using Statement (C# Reference)
using語句確保被處置,即使當你調用對象的方法發生異常調用。將對象放在try塊中,然後在finally塊中調用Dispose,可以獲得相同的結果;實際上,這是編譯器如何翻譯using語句。
一個using
就像是包裹你的代碼在try...finally
,並在最後,所以是的,它應該被稱爲處置。
使用擴展到try..finally塊,所以是的,它會調用Dispose。
在您提供的示例Dispose將在引發異常之前調用。
確保處置被稱爲正常的代碼看起來像
var connection= new SqlConnection(connectionString);
try
{
// do something with the connection here
}
finally
{
connection.Dispose();
}
的usings語句來替換有必要寫這樣一個繁瑣的聲明。
using(var connection = new SqlConnection(connectionString))
{
// do something with the connection here
}
http://stackoverflow.com/questions/1404769/when-would-dispose-method-not-get-called的可能的複製 – SRM 2010-11-24 20:52:52