title: C# multithreading - 'System.Reflection.TargetInvocationException'
body: <p>I started multithread programming in C# (WPF) few days ago and here is a problem which I can't solve... I'm using this piece of code:</p>
  
  <pre><code>    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
      {
          Random foodPosition = new Random();
          double x,y;
          Size size = new Size(30,30);
          bool foodCreated = false;
          Ellipse food = null;
          Food foodObject = null;
          Thread foodThread = new Thread(new ThreadStart(() =&gt;
              {
                  field.Dispatcher.Invoke(new Action(() =&gt;
                  {
                      food = new Ellipse();
                      food.Fill = GenerateColor();
                      food.Width = size.Width;
                      food.Height = size.Height;
                      x = foodPosition.Next(0, (int)(playGroundSize.Width - size.Width) + 1);
                      y = foodPosition.Next(0, (int)(playGroundSize.Height - size.Height) + 1);
                      if (IsFree(x, y, size, 0))
                      {
                          playField.Children.Add(food);
                          Canvas.SetTop(food, y);
                          Canvas.SetLeft(food, x);
  
                          foodObject = new Food(food, new Point(x, y));
                          foodCollection.Add(foodObject,0);
                          foodCreated = true;
                      }
                  }));
  
                  if (foodCreated)
                  {
                      for (int i = 0; i &lt; foodAliveTime; i++)
                      {
                          Thread.Sleep(1000);
                          foodCollection[foodObject]++;
                      }
                      field.Dispatcher.Invoke(new Action(() =&gt;
                      {
                          playField.Children.Remove(foodObject.FoodObject);
                          //threadList[foodObject].Abort();
                      }));
                  }
  
              }));
          foodThread.Start();
      }
  </code></pre>
  
  <p>I think that the problem comes from the upper code. There is an exception thrown after about a minute work of my program. This is the exception:</p>
  
  <blockquote>
    <p>An unhandled exception of type
    'System.Reflection.TargetInvocationException'
    occurred in mscorlib.dll</p>
    
    <p>Additional information: Exception has
    been thrown by the target of an
    invocation.</p>
  </blockquote>
  
  <p>And after that I'm receiving this message:</p>
  
  <blockquote>
    <p>There is no source code available for
    the current location.</p>
  </blockquote>
  
  <p>I know that my source code is a little bit ugly, I'm going to make it better after I solve this problem. Could you please tell me how I can fix the it?</p>