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 um comentário

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:

Reduction operations are those that reduce a collection of values to a single value. In this post, I will share...
I spent the last week talking about RavenDB in San Francisco. By the way, version 4 is out. Also, I...
No último post desta série, tratamos da “Lei do Retorno Acelerado”. Sabemos que negócios digitais tem crescimento potencialmente exponencial. Neste...
In the previous post, I shared some good things about our new query language: RQL. Now, I will show you...
  Este post foi originalmente publicado em meu linkedin. Aqui, revisado e ampliado. Conclui a leitura de um livro fascinante...
Em setembro do ano passado, resolvi assinar a versão digital de um jornal, especializado em economia, de grande circulação no...
× Precisa de ajuda?