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

前端 未结 5 1422
情书的邮戳
情书的邮戳 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:37

    As a complement to @SLaks answer, here's the IL for your code:

    .method private hidebysig static 
        void Main (
            string[] args
        ) cil managed 
    {
        // Method begins at RVA 0x2050
        // Code size 74 (0x4a)
        .maxstack 2
        .entrypoint
        .locals init (
            [0] class [System.Drawing]System.Drawing.Font font3,
            [1] class [System.Drawing]System.Drawing.Font font4,
            [2] bool CS$4$0000
        )
    
        IL_0000: nop
        IL_0001: ldstr "Arial"
        IL_0006: ldc.r4 10
        IL_000b: newobj instance void [System.Drawing]System.Drawing.Font::.ctor(string, float32)
        IL_0010: stloc.0
        .try
        {
            IL_0011: ldstr "Arial"
            IL_0016: ldc.r4 10
            IL_001b: newobj instance void [System.Drawing]System.Drawing.Font::.ctor(string, float32)
            IL_0020: stloc.1
            .try
            {
                IL_0021: nop
                IL_0022: nop
                IL_0023: leave.s IL_0035
            } // end .try
            finally
            {
                IL_0025: ldloc.1
                IL_0026: ldnull
                IL_0027: ceq
                IL_0029: stloc.2
                IL_002a: ldloc.2
                IL_002b: brtrue.s IL_0034
    
                IL_002d: ldloc.1
                IL_002e: callvirt instance void [mscorlib]System.IDisposable::Dispose()
                IL_0033: nop
    
                IL_0034: endfinally
            } // end handler
    
            IL_0035: nop
            IL_0036: leave.s IL_0048
        } // end .try
        finally
        {
            IL_0038: ldloc.0
            IL_0039: ldnull
            IL_003a: ceq
            IL_003c: stloc.2
            IL_003d: ldloc.2
            IL_003e: brtrue.s IL_0047
    
            IL_0040: ldloc.0
            IL_0041: callvirt instance void [mscorlib]System.IDisposable::Dispose()
            IL_0046: nop
    
            IL_0047: endfinally
        } // end handler
    
        IL_0048: nop
        IL_0049: ret
    } // end of method Program::Main
    

    Note the nested try/finally blocks.

提交回复
热议问题