0

(environment: Azure websites. Own, non-shared 1 core instance) I have the following loop which spawns needed number of threads.

    clientIds = comUtility.getAllSyncableClientIds();

    int numOfThreads = clientIds.Count();
    Thread[] exportThreads = new Thread[numOfThreads];

    foreach (int clientId in clientIds)
    {
        offset = offset + 10000; // time to wait
        exportThreads[threadId] = new Thread(() => RunExportToAzureOnItsOwnThread(pId, clientId, offset, threadId));
        exportThreads[threadId].Start();
        threadId++;
    }

Most of the time it seems to work fine. All threads spawn one after another and each thread has its own offset parameter which is just a wait time value called in each individual thread Thread.Sleep(offset); See the results from the log below:

enter image description here

HOWEVER, FOR SOME REASON, ONCE IN A WHILE some of the threads spawn with the same thread number and offset value even though the parameter clientId is supplied properly in the chronological order (see below).

enter image description here

What I do not understand is how could the foreach loop finish with only 1/2 of the functionality within the loop being correct - in this case the loop correctly fetches the next clientId but forgets to increase the offset value.

Thx.

Milan
  • 3,209
  • 1
  • 35
  • 46
  • 4
    You are capturing over a closure. Create a local variable in the `foreach` loop for `offset` and send that into your thread. http://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp – juharr Mar 18 '16 at 14:55
  • 1
    For such a problem ReSharper will tell you "Access to the modified closure". This [question](http://stackoverflow.com/questions/1688465/resharper-warning-access-to-modified-closure) contains more details – Nikita Mar 18 '16 at 14:59
  • ..yes, but since the 'offset' scope is defined in the calling environment and (I am leaving it to the compiler to sort it out ) why would the offset value be the same only sometimes ? – Milan Mar 18 '16 at 15:38
  • ...what i mean is even though the 'offset' has been defined in the foreach object shouldn't the spawned thread object keep reference to the scope chain and preserve the offset value? – Milan Mar 18 '16 at 15:59

0 Answers0