Daniel Daniel - 1 month ago 21x
C# Question

Why is Task.WaitAll not waiting until all of my Tasks have completed? C#

Before I start. I have looked at similar questions and I don't think they have an answer in my situation.

I am having problems with Task.Factory.StartNew and Task.WaitAll.

I am getting null exceptions on a object within a created class that is initialized in the task, even though the code that is throwing a null exception should be waiting until all tasks are complete.

If I run this code without the tasks it works fine.

Why is Task.WaitAll not waiting until all of the Tasks have been completed?

Queue<Task> tasks = new Queue<Task>();
//Go through all transactions in the file via the reader.
foreach (transaction t in xr.read_x12(_progressbar_all_processing)) {
tasks.Enqueue(Task.Factory.StartNew(() => {
//Create a new provider from the current transaction and then
//add it to the global provider list.
provider p = new provider(t);


//Null out the segments of the current transaction
//We are done with them and now the garbage collector
//can clean them up for us.
t.segments = null;

foreach(provider p in t_info.providers){
//Every provider has a List<claims> claims_list
//Do something with p.claims_list
foreach(claim c in p.claims_list){ //<--null exception here



t_info.provider_list is a List<provider> this class is not safe to have multiple threads write to it at once, you must synchronize access to the list.


This will only allow a single thread to do the Add call at a time and will fix your issues with a broken collection.