簡體   English   中英

方法范圍內的資源釋放與.NET中使用塊范圍的資源釋放

[英]Resource releasing in method scope vs using block scope in .NET

哪種方法更有效(時間,內存,資源釋放,異常情況)?

public static string getFileData(string filePath)
{
    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    {
        using (StreamReader r = new StreamReader(fs))
        {
            return r.ReadToEnd();
        }
    }
}

要么

public static string getFileData(string filePath)
    {
        return (new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read)).ReadToEnd());
    }

首先,毫無疑問-您至少要處置正在使用的資源。 在第二種情況下,如果將其存儲在靜態變量中,那么只讀取一次就可以了,但仍然不能勤奮地處理

CLR將為兩個代碼大致生成一個代碼,因此兩個代碼相同

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM