title: Getting wrong results from a Thread
body: <p>I have a small <code>WPF</code> application that needs to enumerate through all files in a specified directory and check if a certain string exists in it. this is the search method:</p>
  
  <pre><code>private void btnSearch_Click_1(object sender, RoutedEventArgs e)
  {
    Thread t = new Thread(()=&gt;search(@"c:\t", "url", true));
    t.Start();
  }
  
  private void search(string path, string textToSearch, bool ignoreCase)
  {
    foreach (string currentFile in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
    {
      int lineNumber = 0;
      foreach (string line in File.ReadLines(currentFile))
      {
        lineNumber++;
        if (line.Contains(textToSearch))
        {
          lbFiles.Dispatcher.BeginInvoke((Action)(() =&gt;
          {
            //add the file name and the line number to a ListBox
            lbFiles.Items.Add(currentFile + "     " + lineNumber);
          }));
        }
      }
    }
  }
  </code></pre>
  
  <p>My problem is that if the specified string is found more than once in the file, the line number will be the latter for all occurrences. for a text file that has the following lines:  </p>
  
  <p><strong>abcd</strong><br>
  <strong>EFG</strong><br>
  <strong>url</strong><br>
  <strong>hijk123</strong><br>
  <strong>url</strong>  </p>
  
  <p>the <code>listbox</code> will look like this:  </p>
  
  <p><img src="https://i.stack.imgur.com/FbDoH.png" alt="ListBoxResult">  </p>
  
  <p>when stepping through the code with a breakpoint I can see that immediately after steping out of the search method it "jumps" back into the <code>BeginInvoke</code> declaration.<br>
  Please advise.<br>
  Thanks</p>