如果using語句中出現異常,資源會被釋放掉嗎?

之前使用using語句一直都有一個疑問就是,如果using語句中出現了異常,那麼using的對象會被釋放掉嗎?比較常見的作法是在using裏面寫try...catch...finally釋放資源。今天就做個實驗來看看資源是否會釋放掉。

1. 創建一個連接類,並實現IDisposable接口

    public class MyConnection : IDisposable
    {

        public void Open()
        {
            Console.WriteLine("MyConnection打開連接");
        }

        public void Dispose()
        {
            Console.WriteLine("MyConnection已被釋放");
        }
    }

2. 創建一個命令類,調用MyConnection

    public class MyCommand
    {
        public void Fun1()
        {
            using (MyConnection conn = new MyConnection())
            {
                conn.Open();
                throw new Exception("");
            }
        }
    }

3. 執行命令

        static void Main(string[] args)
        {
            try
            {
                MyCommand command = new MyCommand();
                command.Fun1();
            }
            catch
            {

            }
            Console.Read();
        }

輸出如下:

可以得出結論,即使在using內部拋出了異常被using的對象還是會被釋放掉的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章