I have an example that I can break every time I use an iterator, but it works fine with a for loop. All code uses variables local to the execution method. I'm at a dead end. There is either a fact about iterators that I donβt know about, or there is an honesty error in .Net. I bet on the first. Please help.
This code works reliably every time. It goes through (letβs say 10) all the elements one by one and starts a new thread, passing an integer to the new thread as an argument in the method. It starts 10 threads, one for each element. 1,2,3,4,5,6,7,8,9,10 - this always works.
WORKING CODE:
//lstDMSID is a populated List<int> with 10 elements. for(int i=0; i<lstDMSID.Count; i++) { int dmsId = lstDMSID[i]; ThreadStart ts = delegate { // Perform some isolated work with the integer DoThreadWork(dmsId); }; Thread thr = new Thread(ts); thr.Name = dmsId.ToString(); thr.Start(); }
And this code actually repeats the elements. It iterates through (letβs say 10) all the elements one at a time and starts a new thread. It starts 10 threads, but does not reliably receive all 10 integers. I see that it starts 1,2,3,3,6,7,7,8,9,10. I am losing numbers.
BUSTED CODE:
//lstDMSID is a populated List<int> with 10 elements. foreach(int dmsId in lstDMSID) { ThreadStart ts = delegate { // Perform some isolated work with the integer DoThreadWork(dmsId); }; Thread thr = new Thread(ts); thr.Name = dmsId.ToString(); thr.Start(); }
Jeremy samuel
source share