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

To write parallel code is not a trivial task. There are details to consider and rules to observe.

Could you say the execution result of the following code? Could you explain why?

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();
    }
}

Share your thoughts in the comments. I will explain what is going on in a future post.

Compartilhe este insight:

3 respostas

  1. 1. Could you say the execution result of the following code ?
    ANSWER : 10 .
    2. Could you explain why ?
    ANSWER : I think: “MAIN thread” runs faster than “NEW thread” (Task.Factory.StartNew). When it gets the value of “i” (main thread) ends is 10, each new thread created (Task.Factory.StartNew) gets the value 10 and writes 10 times (each thread).

  2. It depends on the compiler version you use. For example, in version 4 the result will be 10 for each task however in version 5 it will be the value of i in each iteration. As the closure will capture the variable and the scope of the variable is the key.

    Marc’s Gravell explanation how both compiler versions differ: “It comes down to where the l-value is declared. In the 2.0 spec, the l-value was stated in the specification as being outside the loop – i.e. how foreach is expanded to actual code (while). In the later spec (and, oddly, in the 1.2 spec appendix for “definite assignment”, IIRC) it is stated as being inside the loop. The captured variable logic is very sensitive to scope; inside=per iteration; outside=global to the loop.”

    The compiler will create a class for the closure, and if the captured variable is local to the loop, we get one instance for each loop iteration, however, if the variable is global to the lopp, you will get the same instance invoked and the value of the captured variable is updated at each iteration. So you will end up with the same value for each invocation.

    Ref: https://stackoverflow.com/a/5438331/1480159

    Storing i value in a temp variable and pass that temp variable to the action will fix:

    for (var i = 0; i WriteLine(temp ));
    }

  3. 1. ANSWER : 10 .
    2. ANSWER : I think: “MAIN thread” runs faster than “NEW thread” (Task.Factory.StartNew). When it gets the value of “i” (main thread) ends is 10, each new thread created (Task.Factory.StartNew) gets the value 10 and writes 10 times (each thread).

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

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:

As you probably noted, my old blog posts are gone! It’s sad, but I had to take this way. Main reasons:...
In the previous post, I shared an example of how containers could help us to make the code clearer about...
Neste post mostro como implementar um EventBus, utilizando RabbitMQ, em C#. Este código ainda está em desenvolvimento. Em breve, uma...
Implementing a good caching strategy is fundamental to achieve good performance. Besides that, it is not a trivial task. There...
Crescer implica, invariavelmente, em aumentar a produtividade, ou seja, na melhoria da relação entre a capacidade de gerar valor e...
Este é o primeiro post da série em que vou compartilhar algum conhecimento sobre como desenvolver uma aplicação de verdade...