ANSWER: Could you explain the execution result of this code?

 

Recently, I asked what would be the execution result of the following code:

using System.Threading.Tasks;
using static System.Console;
class Program
{
    static void Main()
    {
        for (var i = 0; i < 10; i++) 
        { 
            Task.Factory.StartNew(() => WriteLine(i));
        }

        ReadLine();
    }
}

So, here it is:

At first view, it seems weird, as you may well have expected to see unique values from 0 to 9. Instead, the same value is printed out multiple times. What is going on?

We need to talk about closures

The reason why the execution result of the previous code was ten 10s on the screen lies with the closure. Are you familiar with this concept? If not, please, read this article.

The compiler will make the value of the variable i (which is in the stack) available to the lambdas capturing the local variable and placing it into a compiler-generated object on the heap. That object will be referenced inside of each lambda.

.method private hidebysig static
void Main () cil managed 
{
        // Method begins at RVA 0x2050
        // Code size 71 (0x47)
        .maxstack 3
        .entrypoint
        .locals init (
                [0] class Program/'<>c__DisplayClass0_0',
                [1] int32
        )
        // (no C# code)
        IL_0000: newobj instance void Program/'<>c__DisplayClass0_0'::.ctor()
        IL_0005: stloc.0
        IL_0006: ldloc.0
        // for (i = 0; i < 10; i++)
        IL_0007: ldc.i4.0
        // (no C# code)
        IL_0008: stfld int32 Program/'<>c__DisplayClass0_0'::i
        IL_000d: br.s IL_0036    // loop start (head: IL_0036)
        //         Task.Factory.StartNew(delegate
        //         {
        //             Console.WriteLine(i);
        //         });
        IL_000f: call class [System.Runtime]System.Threading.Tasks.TaskFactory [System.Runtime]System.Threading.Tasks.Task::get_Factory()
        IL_0014: ldloc.0
        IL_0015: ldftn instance void Program/'<>c__DisplayClass0_0'::'b__0'()
        // (no C# code)
        IL_001b: newobj instance void [System.Runtime]System.Action::.ctor(object, native int)
        IL_0020: callvirt instance class [System.Runtime]System.Threading.Tasks.Task [System.Runtime]System.Threading.Tasks.TaskFactory::StartNew(class [System.Runtime]System.Action)
        IL_0025: pop
        IL_0026: ldloc.0
        IL_0027: ldfld int32 Program/'<>c__DisplayClass0_0'::i
        IL_002c: stloc.1
        IL_002d: ldloc.0
        IL_002e: ldloc.1
        // for (i = 0; i < 10; i++)
        IL_002f: ldc.i4.1
        // (no C# code)
        IL_0030: add
        IL_0031: stfld int32 Program/'<>c__DisplayClass0_0'::i
        IL_0036: ldloc.0
        IL_0037: ldfld int32 Program/'<>c__DisplayClass0_0'::i
        // for (i = 0; i < 10; i++)
        IL_003c: ldc.i4.s 10
        IL_003e: blt.s IL_000f
        // end loop
        // Console.ReadLine();
        IL_0040: call string [System.Console]System.Console::ReadLine()
        IL_0045: pop
        // (no C# code)
        IL_0046: ret
}
// end of method Program::Main

As the local variable is declared outside the loop body, the capture point is, therefore, also outside the loop body. A unique object will be instantiated! As a single object is used to store all the increments of the variable, each task will share the same closure object. Considering that the first task will start to run after the loop is completed, the value of the variable will be 10. Got it?

But, how to print out all the numbers from 0 to 9, not necessarily in order? Here is the answer:

using System.Threading.Tasks;
using static System.Console;
class Program
{
    static void Main()
    {
        for (var i = 0; i < 10; i++)
        { 
            var varToCapture = i;
            Task.Factory.StartNew(() => WriteLine(varToCapture));
        }

        ReadLine();
    }
}

Now, the capturing point occurs inside the loop. In this way, a new (and different) object will be instantiated for each task.

Nice!

Compartilhe este insight:

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

In the previous post, I shared some good things about our new query language: RQL. Now, I will show you...
If you ask me one tip to improve the performance of your applications, it would be: Design your objects to...
Implementing synchronization for multiple threads in .NET is easy. There are a lot of options for doing that – for...
No post anterior, compartilhei um exemplo de como containers podem nos ajudar a deixar o código mais claro sobre os...
The type EmbeddableDocumentStore is gone. But it does not mean that you have no good options to replace his functionality....
Tem coisas que a gente até sabe, mas ignora pela vaidade… Uma das features mais aclamadas do Microsoft Teams, para...

Inscrição realizada com sucesso!

No dia da masterclass você receberá um e-mail com um link para acompanhar a aula ao vivo. Até lá!

A sua subscrição foi enviada com sucesso!

Aguarde, em breve entraremos em contato com você para lhe fornecer mais informações sobre como participar da mentoria.

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano anual do Clube de Estudos:

Crie sua conta

Preencha os dados para iniciar o seu cadastro no plano mensal do Clube de Estudos:

× Precisa de ajuda?