0
   Parallel.For<string>(0, 20, () =>
    {
        // invoked once for each thread
        Console.WriteLine("init thread {0}, task {1}", Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
        return String.Format("t{0}",
        Thread.CurrentThread.ManagedThreadId);
    }, (i, pls, str1) =>
    {
        // invoked for each member
        Console.WriteLine("body i {0} str1 {1} thread {2} task {3}", i, str1,
        Thread.CurrentThread.ManagedThreadId, Task.CurrentId);
        Thread.Sleep(10);
        return String.Format("i {0}", i);
    }, (str1) =>
    {
        // final action on each thread
        Console.WriteLine("finally {0}", str1);
    });

I got these code from the book 《Professional C# 5.0 and .NET 4.5.1》, and the book shows the result at page 560 :

enter image description here

I think the result where I around it with red retangle may be wrong, It should be "body i 1 str1 t1 thread 1 task 1", Is that I comprehend these right? or I was wrong about that. Is there anyone can explain these to me ? thanks

4

1 回答 1

0

I think you're correct. Breaking down the code:

The first anonymous function is called once per thread, and returns the initial state in this line:

return String.Format("t{0}", Thread.CurrentThread.ManagedThreadId);

So for each thread, the initial state is in the format t#. That state is then passed into the second anonymous function as parameter str1. The second anonymous function prints out some information (including the value of str1) and then returns a new state value:

return String.Format("i {0}", i);

This gets passed into the next iteration executed by the same thread.

Since each thread's state is initialized to the format t#, the first body statement printed by each thread should have a value of str1 in that format. Only subsequent body statements from that thread should have a value of str1 in the format i #.

于 2016-03-10T04:48:36.793 回答