adi sba
adi sba

Reputation: 621

Parellel.ForEach error

I have an array of threads which i want run in simultaneous/parallel but i get "NullReferenceException"

var t = new Thread[6];
t[0] = new Thread(() => DoSomething0());
t[1] = new Thread(() => DoSomething1());
t[2] = new Thread(() => DoSomething2());
t[3] = new Thread(() => DoSomething3());
t[4] = new Thread(() => DoSomething4());
t[5] = new Thread(() => DoSomething5());
Parallel.ForEach(t, item => item.Start());

It gives error at Parrallel.Foreach because item is null but what am i doing wrong?

Upvotes: 1

Views: 108

Answers (3)

Justin Pihony
Justin Pihony

Reputation: 67135

You have an array instantiated with 6 slots (all initially null), and you only instantiate the first 5 slots, leaving the 6th null. This would be your null item.

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98858

You defined 6 elements but you assign only 5 elements, last element is null now.

That's why you get NullReferanceException when you try to use all of them.

Initialize also 6th element.

t[0] = new Thread(() => DoSomething0());
t[1] = new Thread(() => DoSomething1());
t[2] = new Thread(() => DoSomething2());
t[3] = new Thread(() => DoSomething3());
t[4] = new Thread(() => DoSomething4());
t[5] = new Thread(() => DoSomething5());

Upvotes: 1

Guffa
Guffa

Reputation: 700800

You create an array for six items, but you only assign values to the first five. The last item is null, so you get a null reference error when you try to use all items in the array.

Upvotes: 1

Related Questions