回答

3

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

using語句確保被處置,即使當你調用對象的方法發生異常調用。將對象放在try塊中,然後在finally塊中調用Dispose,可以獲得相同的結果;實際上,這是編譯器如何翻譯using語句。

1

不,不需要。我們的網絡服務專家只是爲了確保您關注。

+1

您應該準確地解釋爲什麼它不是必需的 - 即並非所有程序都需要在100%的時間內完美運行,並且如果您的業務需求指定了緩慢的資源泄漏,那麼忽略它就是完成此任務的票據。 –

+0

@Jesse:非常好的一點。另一個省略它的原因是,如果你想要像「數據庫已經打開」這樣的隨機錯誤,由於你上次沒有處理它。 –

0

要回答你的問題,這裏有一些例子來說明using語句更常見的用法,以確保在其他的答案中引用的處理「是什麼using語句呢?」:

確保的StringWriter和XmlTextWriter的設置(關閉),當我們使用完:

using (StringWriter sw = new StringWriter(sb)) 
     using (XmlTextWriter xw = new XmlTextWriter(sw)) 
     { 
      WebPartManager1.ExportWebPart(partToExport, xw); 
     } 

確保了數據庫連接和命令對象設置:

DataTable dt = new DataTable(); 

using (SqlConnection connection = new SqlConnection("ConnectionString")) 
using (SqlCommand command = new SqlCommand()) 
{ 
    command.Connection = connection; 
    command.CommandText = "SELECT * FROM Customers"; 

connection.Open(); 
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) 
{ 
    dt.Load(reader); 
} 
} 
+0

-1:請修復上面的SqlCommand對象,並請使用XmlWriter.Create而不是XmlTextReader。 –

+0

@John Saunders:我不會將這些作爲他們特定用法的「最佳實踐」,只是作爲「使用」語句的常見應用程序的示例。你能用我的SqlCommand來詳細說明你的問題嗎?喜歡,哪一個? – DOK

+0

@DOK:將複製和粘貼示例。 **總是**在示例中正確使用IDisposable,否則那些複製「只是一個示例」的代碼將會有錯誤代碼。修復任何不在使用塊中的SqlCommand!這和其他所有實現IDisposable的方法(可能的DataTable除外)。 –