StefanG
StefanG

Reputation: 1264

c# Parallel Processing throws NullReference Exception in task resource

I try to parallelize the processing of my data. Therefore I initialize for every parallel task a Processor object with the localInit parameter. It works fine in the first iteration for every task, but on the second iteration I get always a NullReferenceException.

The docu says for the local Init parameter in Parallel.ForEach:

localInit:
//     The function delegate that returns the initial state of the local data for
//     each task.

So, what I do wrong?

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
    );
}

Upvotes: 0

Views: 1059

Answers (2)

VarunMehra
VarunMehra

Reputation: 26

I tried doing this and this works fine for me. Can you run this and tell me if you are still getting an exception?

static void Main(string[] args)
        {
            Program p = new Program();
            p.ParallelThings();
        }


        Processor GetMyProcessor()
        {
            Processor processor = new Processor();
            // Some initialization
            return processor;
        }

        void ParallelThings()
        {
            IEnumerable<MyClass> myData = new List<MyClass>() { new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass()
    ,new MyClass(),new MyClass(),new MyClass(),new MyClass(),new MyClass(),new MyClass()};
            Parallel.ForEach(
                    myData,
                    new ParallelOptions { MaxDegreeOfParallelism = 8 },
                    GetMyProcessor,
                    (data, state, processor) =>
                    {
                        //  Console.WriteLine(DateTime.Now);
                        return processor.DoSomething(); // <---- NO exception
                    },
                    (item) => { } //Nothing to do for the moment
              );
        }

Upvotes: 1

Rufus L
Rufus L

Reputation: 37020

I don't know if this helps your situation because you appear to be using a different overload of ForEach than I usually use. But what if you call GetMyProcessor inside the function that's acting on the items in your myData collection, something like:

Parallel.ForEach(myData, 
    new ParallelOptions {MaxDegreeOfParallelism = Environment.ProcessorCount},
    dataItem =>
    {
        var processor = GetMyProcessor();
        processor.DoSomething(dataItem);
    });

Upvotes: 0

Related Questions