关于Task.StartNew(Action< Object> ;, Object)方法 [英] About the Task.StartNew(Action<Object>, Object) method
问题描述
我正在此页面上学习TPL,一个代码块使我非常困惑.
I'm learning the TPL on this page, and one code block confuses me a lot.
我正在阅读此页:任务并行(任务并行库)
在一节中,它说下面的代码是正确的解决方案,因为循环中的lambda每次迭代后都无法获得其值,而最终值却无法获得.因此,您应该将"i"包装在CustomData对象中.代码如下:
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:
在Task.Factory.StartNew()方法中,作者使用其重载形式之一:
in the Task.Factory.StartNew() method, the author uses one of its overload form:
Task.StartNew(Action<Object>, Object)
我很想知道"obj"来自哪里?它如何具有3个属性:名称,CreationTime和ThreadNum.
I am so curious to know where does the "obj" come from? How does it have 3 properties: Name, CreationTime and ThreadNum.
我在MSDN上搜索时发现没有有用的详细信息,但这是:一个包含要由动作委托使用的数据的对象." MSDN 确实没有解释任何事物.
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.
有人可以解释吗?
推荐答案
下面是一个更简洁的示例,可能有助于对其进行解释.
Here is a more concise example which may help to explain it.
void StartNew(Action<object> action, object o) {
action(o);
}
StartNew
方法仅接受action
委托,并通过传递o
作为参数来调用它.传递给lambda的值就是在lambda之后传递给StartNew
的值
The StartNew
method just takes the action
delegate and invokes it by passing o
as the parameter. The value passed to the lambda is simply the value that is passed into StartNew
after the lambda
// Prints "hello world"
StartNew(o => Console.WriteLine(o), "hello world");
在您概述第二个参数为
new CustomData() {Name = i, CreationTime = DateTime.Now.Ticks}
这只是创建一个类型为CustomData
的新对象,为其分配一些属性,并将其作为紧接在其之前定义的lambda的参数.最终它将成为lambda值obj
This just creates a new object of type CustomData
, assigns it some properties and makes it the argument to the lambda defined immediately before it. It will eventually become the value obj
in the lambda
这篇关于关于Task.StartNew(Action< Object> ;, Object)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!