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:

Eventualmente, é bom revisitar alguns temas clássicos de ciências da computação. Nesse post, vamos ver como detectar o nodo de...
Há quase um mês, resolvi intensificar a comunicação da EximiaCo, dessa vez, em um canal dedicado ao público técnico, no...
Our goal is to fill a two-dimensional array with 1’s. using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Running; namespace ToArrays { public class Program...
The type EmbeddableDocumentStore is gone. But it does not mean that you have no good options to replace his functionality....
In this post, I’m going to share with you one of the RavenDB 4 features that I like the most:...
What kind of optimizations could we expect from the C# compiler and the JIT? In this post, I would like...
× Precisa de ajuda?