title: Passing value parameter to Task in c#
body: <p>I have an issue with passing a long by value to a Task.</p>
  
  <p>I have a list of ID's where I loop through each one, assign to a local variable then pass as a parameter to a new Task. I do not wait for the task to complete before looping round and processing the next ID. I keep an array of Tasks but this is irrelevant.</p>
  
  <pre><code>loop
      long ID = list[index];
      task[index] = Task.Factory.StartNew(() =&gt; doWork(ID));
  end loop
  </code></pre>
  
  <p>If the list contained for example 100 and 200. I would want the first task called with 100 
  then the second task called with 200. But it does not, doWork receives 200 for both tasks so there is an issue when the value is copied. </p>
  
  <p>I can demonstrate with some simple console code</p>
  
  <pre><code>class Program
  {
     static void Main(string[] args)
     {
        long num = 100;
        Task one = Task.Factory.StartNew(() =&gt; doWork(num));
        num = 200;
  
        Console.ReadKey();
     }
  
     public static void doWork(long val)
     {
        Console.WriteLine("Method called with {0}", val);
     }
   }
  </code></pre>
  
  <p>The above code will always display</p>
  
  <p>Method called with 200</p>
  
  <p>I modified the code to wait for the task status to switch from WaitingToRun </p>
  
  <pre><code>static void Main(string[] args)
  {
     long num = 100;
     Task one = Task.Factory.StartNew(() =&gt; doWork(num));
     while(one.Status == TaskStatus.WaitingToRun)
     {}
     num = 200;
  
     Console.ReadKey();
  }
  </code></pre>
  
  <p>This improves things but not 100% proof, after a few runs I got  Method called with 200</p>
  
  <p>Also tried the following</p>
  
  <pre><code>while (true)
  {
      if (one.Status == TaskStatus.Running | one.IsCompleted == true)
      break;
  }
  </code></pre>
  
  <p>but again got 200 displayed.</p>
  
  <p>Any ideas how you can guarantee the value passed to the task without waiting for the task to complete?</p>
  
  <p>Any help/ suggestions appreciated
  Ade</p>