Home [C# 筆記] 使用 using 來釋放資源
Post
Cancel

[C# 筆記] 使用 using 來釋放資源

finally 區塊裡面可以使用 reader.Dispose() 來釋放檔案資源,這是 .NET 程式很常見的寫法。其實不只是檔案,其他像是網路連線、資料庫連線等等,這些都是屬於無法由 .NET 執行環境自動回收的資源(即所謂的 unmanaged resources),故必須在寫程式的時候明確呼叫特定的方法來釋放資源。由於釋放資源是相當常見的工作,於是 .NET 基礎類別庫定義了一個介面來規範一致的寫法: System.IDisposable。此介面只定義了一個方法,即用來釋放資源的 Dispose。

也就是說,只要是用來處理 unmanaged resources 的類別(例如剛才提到的檔案、資料庫連線等等),都必須實作 IDisposable,以便在適當時機呼叫 Dispose 方法來釋放物件所占用的資源。於是,我們經常會撰寫類似底下的程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
StreamReader reader = null;
try
{
    reader = new StreamReader("app.config");
    ...
}
finally
{
    if (reader != null)
    {
        reader.Dispose();
    }    
}

上述寫法堪稱標準範本,只是程式碼超過 10 行,顯得過於繁瑣、笨重。因此,C# 提供了一個簡便的語法:using 宣告,讓我們能夠用一行程式碼就完成上述工作:

1
using var reader = new StreamReader("app.config");

或者你也可以加上一對大括弧來明確限定物件的存活範圍:

1
2
3
4
using (var reader = new StreamReader("app.config"))
{
    ... // 在此區塊內皆可使用 reader 物件
}

一旦程式離開了 using 區塊,reader 就會被自動釋放(自動呼叫其 Dispose 方法)。

那麼,如果使用了單行 using 宣告的語法,reader 物件又是何時釋放呢?
答案是:在它所屬的區塊結束時。請看以下範例:

1
2
3
4
5
if (File.Exists("app.config"))
{
    using var reader = new StreamReader("app.config");
    Console.WriteLine(reader.ReadToEnd());
}

當程式離開 if 區塊時,reader 便會自動釋放。

C# 例外處理(Exception Handling) by huanlintalk
[C# 筆記] using 關鍵字的作用 by R

This post is licensed under CC BY 4.0 by the author.