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 asked why the following code behaves differently when compilation is made in Release and Debug...
In a previous post, I started an elementary search library using C#. Now, I will improve it adding a Porter...
Tentando ser “Júnior” Minha carreira como amador remunerado em programação começou em 1992. Eu tinha quase 13 anos e era...
Implementing a good caching strategy is fundamental to achieve good performance. Besides that, it is not a trivial task. There...
Are you interested to know more about the internals of the .NET Runtime? So you should spend some time reading...
Let’s have fun with prime numbers? In this post, I would like to share some results I got from using...

Curso Reputação e Marketing Pessoal

Masterclasses

01

Introdução do curso

02

Por que sua “reputação” é importante?

03

Como você se apresenta?

04

Como você apresenta suas ideias?

05

Como usar Storytelling?

06

Você tem uma dor? Eu tenho o alívio!

07

Escrita efetiva para não escritores

08

Como aumentar (e manter) sua audiência?

09

Gatilhos! Gatilhos!

10

Triple Threat: Domine Produto, Embalagem e Distribuição

11

Estratégias Vencedoras: Desbloqueie o Poder da Teoria dos Jogos

12

Análise SWOT de sua marca pessoal

13

Soterrado por informações? Aprenda a fazer gestão do conhecimento pessoal, do jeito certo

14

Vendo além do óbvio com a Pentad de Burkle

15

Construindo Reputação através de Métricas: A Arte de Alinhar Expectativas com Lag e Lead Measures

16

A Tríade da Liderança: Navegando entre Líder, Liderado e Contexto no Mundo do Marketing Pessoal

17

Análise PESTEL para Marketing Pessoal

18

Canvas de Proposta de Valor para Marca Pessoal

19

Método OKR para Objetivos Pessoais

20

Análise de Competências de Gallup

21

Feedback 360 Graus para Autoavaliação

22

Modelo de Cinco Forças de Porter

23

Estratégia Blue Ocean para Diferenciação Pessoal

24

Análise de Tendências para Previsão de Mercado

25

Design Thinking para Inovação Pessoal

26

Metodologia Agile para Desenvolvimento Pessoal

27

Análise de Redes Sociais para Ampliar Conexões

Lições complementares

28

Apresentando-se do Jeito Certo

29

O mercado remunera raridade? Como evidenciar a sua?

30

O que pode estar te impedindo de ter sucesso

Recomendações de Leituras

31

Aprendendo a qualificar sua reputação do jeito certo

32

Quem é você?

33

Qual a sua “IDEIA”?

34

StoryTelling

35

Você tem uma dor? Eu tenho o alívio!

36

Escrita efetiva para não escritores

37

Gatilhos!

38

Triple Threat: Domine Produto, Embalagem e Distribuição

39

Estratégias Vencedoras: Desbloqueie o Poder da Teoria do Jogos

40

Análise SWOT de sua marca pessoal

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.

Masterclass
15/07

Pare de dar a solução certa para o problema errado

Muita gente boa quebra a cabeça por dias tentando resolver o que não estava quebrado, simplesmente por tentar dar a resposta certa pro problema errado, mas precisa realmente ser assim?

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?