I'm learning the TPL on this page, and one code block confuses me a lot.
I was reading this page: Task Parallelism (Task Parallel Library)
in one section, it said that the following code is the right solution because a lambda in a loop can't get the value as it mutates after each iteration, but the final value. So you should wrap the "i" in a CustomData object. The code is below:
class CustomData
{
public long CreationTime;
public int Name;
public int ThreadNum;
}
public class Example
{
public static void Main()
{
// Create the task object by using an Action(Of Object) to pass in custom data
// to the Task constructor. This is useful when you need to capture outer variables
// from within a loop.
Task[] taskArray = new Task[10];
for (int i = 0; i < taskArray.Length; i++)
{
taskArray[i] = Task.Factory.StartNew( (Object obj ) =>
{
CustomData data = obj as CustomData;
if (data == null)
return;
data.ThreadNum = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine("Task #{0} created at {1} on thread #{2}.", data.Name, data.CreationTime, data.ThreadNum);
},
new CustomData()
{
Name = i,
CreationTime = DateTime.Now.Ticks
});
}
Task.WaitAll(taskArray);
}
}
The code is rather straightforward and easy to understand but here comes my problem:
in the Task.Factory.StartNew() method, the author uses one of its overload form:
Task.StartNew(Action<Object>, Object)
I am so curious to know where does the "obj" come from? How does it have 3 properties: Name, CreationTime and ThreadNum.
I searched over MSDN found no useful detail but this: "An object containing data to be used by the action delegate." MSDN It really doesn't explain anything.
Could anyone explain it?