Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem is that you are creating closure over the loop variable <code>i</code> and using its value later on, after the loop has progressed.</p> <p>When creating a lambda function with <code>() =&gt; ProcessJob(jobs[i], i)</code> the compiler creates a hidden reference to the variable <code>i</code> which is updated by the <code>for</code> loop. The same reference is read when <code>ProcessJob</code> is called as part of the task being executed.</p> <p>The behavior you see is the result of a race condition: even though you are starting the tasks <em>inside</em> the loop, those tasks run on separate threads and the threads do not start executing immediately. When they <em>do</em> start the value of <code>i</code> has been modified (because more iterations of the loop have been completed) and the value read by <code>ProcessJob</code> is "wrong".</p> <p>The version with the <code>index</code> variable creates a <em>local copy</em> of <code>i</code> which is logically separate from it and is not modified together with <code>i</code>; this copy is therefore immune to being changed before the task has a chance to start. You would get the same (correct) behavior with:</p> <pre><code>var index = i; // Note that tasks[index] can also be tasks[i] -- it makes no difference // because that value is used strictly during the current loop iteration tasks[index] = new Task(() =&gt; ProcessJob(pJobsToExecute[index], index)); tasks[index].Start(); </code></pre> <p>Creating a local copy of captured variables as above is the solution to all problems of this type.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload