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:

Decidi aprender a programar com R. Aqui está algo que escrevi. ## defining a function makeCacheMatrix <- function(x = matrix())...
Last year, Mario Fusco wrote a blog post series questioning the way Java developers are implementing the Gang of Four (GoF) patterns....
Um dos princípios que mais valorizo em práticas ágeis é o feedback. De todos os tipos de feedback que já...
This is the first of a series of blog posts sharing some knowledge about how to develop a real-world software...
Eventualmente, é bom revisitar alguns temas clássicos de ciências da computação. Nesse post, vamos ver como detectar o nodo de...
Nossos códigos precisam ser fáceis de compilar e testar. Para isso, nada melhor do que começarmos da forma certa, com...