I am starting atmost 5 threads in a program in C# .NET. But sometimes some of those threads just quit or become dead inexplicably even before the completion of execution of the function assigned to it.
It happens randomly . If I try to debug the code by putting breakpoints- It works fine.
And sometimes all the threads execute the assigned functions perfectly.They do not share any resources among them.
Thread[] td = new Thread[5]; for (count = 4; count >= 0; --count) { ds[count] = dba.getData(ru[count]); td[count] = new Thread(delegate() { runRule[count].performTask(ru[count], ds[count], count); }); td[count].Name = 'Thread ' + count.ToString(); td[count].Start(); Thread.Sleep(50); }
If I remove the last line ‘Thread.Sleep(50)’ only the first thread stared runs and rest of them just die.
can someone explain why the threads are becoming dead?
I suspect they’re not becoming dead – I suspect the problem is that you’re not actually running the rules you think you are. When you use a method’s local variables within an anonymous method, the variables themselves are captured. In this case, you’re capturing the
countlocal variable – and then changing it (as the loop counter decreases). By the time a thread created when count=4 starts running,countmay be 3 – so it will be callingrunRule[3].performTask(ru[3], ds[3], 3). In fact,countcould change while the expressions are being evaluated which could cause a lot of fun.The way to get round this is to have a different ‘local’ variable for each iteration of the loop. It’s easy to do:
Now the only variables being captured in the delegate are
copyandrunRule/ru/ds– I’m assuming that the latter three don’t change. A new ‘instance’ of thecopyvariable is created each time you go round the loop, so changes won’t interfere with each other.See whether this helps – it’s at least a potential cause for massive confusion, and may well be the problem.