Can “using” with more than one resource cause a resource leak?

前端 未结 5 1420
情书的邮戳
情书的邮戳 2020-12-04 15:10

C# lets me do the following (example from MSDN):

using (Font font3 = new Font(\"Arial\", 10.0f),
            font4 = new Font(\"Arial\", 10.0f))
{
    // Use         


        
5条回答
  •  青春惊慌失措
    2020-12-04 15:23

    Here is a sample code to prove @SLaks answer:

    void Main()
    {
        try
        {
            using (TestUsing t1 = new TestUsing("t1"), t2 = new TestUsing("t2"))
            {
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine("catch");
        }
        finally
        {
            Console.WriteLine("done");
        }
    
        /* outputs
    
            Construct: t1
            Construct: t2
            Dispose: t1
            catch
            done
    
        */
    }
    
    public class TestUsing : IDisposable
    {
        public string Name {get; set;}
    
        public TestUsing(string name)
        {
            Name = name;
    
            Console.WriteLine("Construct: " + Name);
    
            if (Name == "t2") throw new Exception();
        }
    
        public void Dispose()
        {
            Console.WriteLine("Dispose: " + Name);
        }
    }
    

提交回复
热议问题