.NET Quiz

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.

More posts in .NET Quiz series

3 Comments
  1. Juan Cezario

    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. Luís Barbosa

    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. Juan Cezario

    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).

Leave a Reply

Your email address will not be published. Required fields are marked *