I have a Windows service that spawns objects that do work. The objects have two methods that get kicked off as Tasks. During housekeeping or shutdown, I call a Stop method on the object that tell the Tasks to stop. I have a list of the Tasks created for the objects' methods, so I do a Task.WaitAll for them. But, I'm getting a NullReferenceException during shutdown. I thought one of the Task objects was null, so I tested for it with a .Where(pt => pt != null).ToArray(), but that didn't work.
Here's a snippet:
var peProcessor = new PrintExpertProcessor(runId);
processorTasks.Add(Task.Factory.StartNew(() => peProcessor.ProcessRun()));
processorTasks.Add(Task.Factory.StartNew(() => peProcessor.StartMonitor()));
processors.Add(peProcessor);
// Later in the code
Task.WaitAll(processorTasks.ToArray()); // System.AggregateException: System.NullReferenceException:
I think that the Task is not null, but that the original processor object is null. But, I'm not sure how to check that or prevent this. I'm new to Tasks, so I'm still getting my head around it.
Thoughts?
Full Error Message:
System.AggregateException: System.NullReferenceException: Object reference not set to an instance of an object.
at WOW.PrintExpert.AwdProcessor.Code.PrintExpertProcessor.StopProcessor()
at WOW.PrintExpert.AwdProcessor.Code.PrintExpertProcessor.ProcessRun()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken)
at WOW.PrintExpert.AwdProcessorService.ProcessorService.OnStop()
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
at WOW.PrintExpert.AwdProcessor.Code.PrintExpertProcessor.StopProcessor()
at WOW.PrintExpert.AwdProcessor.Code.PrintExpertProcessor.ProcessRun()
at System.Threading.Tasks.Task.Execute()<---
Task.Runinstead ofTask.Factory.StartNew