我尝试并行处理我的数据。 因此,我使用localInit参数为每个并行任务初始化一个Processor对象。 它在每个任务的第一次迭代中工作正常,但在第二次迭代中,我总是得到一个NullReferenceException。c#并行处理抛出任务资源中的NullReference异常
的实况说,在Parallel.ForEach当地的初始化参数:
localInit:
// The function delegate that returns the initial state of the local data for
// each task.
所以,我做错了什么?
Processor GetMyProcessor()
{
Processor processor = new Processor();
// Some initialization
return processor;
}
void ParallelThings()
{
IEnumerable<MyClass> myData = ...;
Parallel.ForEach(
myData,
new ParallelOptions { MaxDegreeOfParallelism = 8 },
GetMyProcessor,
(data, state, processor) =>
{
processor.DoSomething(); // <---- Null reference exception
},
(item) => {} //Nothing to do for the moment
);
}
是的,你知道了!现在我理解了这个概念:资源从迭代转移到迭代。你只需要返回它。我将其修改为: processor.DoSomething();返回处理器; 由于我没有返回任何东西,它是空的! – StefanG 2014-10-10 13:40:09