[英]Disposables, Using & Try/Catch Blocks
今天有一個心理障礙,需要一只手驗證我的邏輯並不是很好的。
傳統上我會做類似這樣的文件i / o:
FileStream fs = null; // So it's visible in the finally block
try
{
fs = File.Open("Foo.txt", FileMode.Open);
/// Do Stuff
}
catch(IOException)
{
/// Handle Stuff
}
finally
{
if (fs != null)
fs.Close();
}
但是,這不是很優雅。
理想情況下,當我完成時,我想使用using
塊來處理文件流,但我不確定using和try / catch之間的協同作用。
這就是我想要實現上述內容的方式:
try
{
using(FileStream fs = File.Open("Foo.txt", FileMode.Open))
{
/// Do Stuff
}
}
catch(Exception)
{
/// Handle Stuff
}
但是,我擔心使用塊中的過早退出(通過拋出異常)可能不允許使用塊完成執行並清理它的對象。 我只是偏執狂,還是會按照我打算的方式運作?
你只是偏執狂,它會像你想要的那樣工作:)
using語句相當於try / finally塊,無論它是否在try / catch中。
所以你的代碼類似於:
try
{
FileStream fs = null;
try
{
fs = File.Open("Foo.txt", FileMode.Open);
// Do stuff
}
finally
{
if (fs != null)
{
fs.Dispose();
}
}
}
catch(Exception)
{
/// Handle Stuff
}
不用擔心,它會按預期清理並且比原來更清潔。
事實上,在業務邏輯中使用try / finally aka using語句,在UI層或物理層邊界的頂級處理程序中使用try / catch更為常見。 就像是:
try
{
DoStuffWithFile("foo.txt");
}
catch(Exception ex)
{
...
}
和
public void DoStuffWithFile(string fileName)
{
using(FileStream fs = File.Open(fileName,...))
{
// Do Stuff
}
}
這將起作用 - 在內部,using語句編譯方式與try-finally塊相同
try
{
FileStream fs = null;
try
{
fs = File.Open("Foo.txt", FileMode.Open);
}
finally
{
fs.Dispose();
}
}
catch(Exception)
{
/// Handle Stuff
}
第二段代碼被翻譯成這個
使用塊將完全按照您所說的轉換使用塊實際上正常工作
try
{
FileStream fs = null;
try
{
fs = File.Open("Foo.txt", FileMode.Open))
//Do Stuff
}
finally
{
if(fs != null)
fs.Dispose();
}
}
catch(Exception)
{
/// Handle Stuff
}
如果你有一個using()
你不需要try..finally
。 他們執行相同的操作。
如果您不相信,請將Reflector指向裝配體並比較生成的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.