title: Background Worker will not start after RunWorkerAsync()
body: <p>New to C# - I've pieced together some parts of code from an example project I found online that is close to what I'm trying to accomplish - and it refuses to behave the same way.  So far I've learned a lot and done a lot of tweaking, but this piece continues to elude me and I can't find anything quite the same online.  In the example program, the backgroundWorker.RunWorkerAsync(); jumps right to the next part of the program.  In my code, it won't.  I've placed breaks at many different places, and it always stops and seems to hang at RunWorkerAsync().  I think part of the problem is that the way the original author of the example program used the background worker doesn't line up with most of the examples I see online...but it works in the example program when I run it on its own.  What am I missing?</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Text;
  using System.Windows.Forms;
  using System.IO;
  using System.Text.RegularExpressions;
  
  namespace DIPUtil
  {
  public partial class DIPform : Form
  {
      #region Fields
      private string outputDirectory;
      protected string findWhatString = "BEGIN";
      protected string replaceWithText = "FANOODLE";
  
  
      #endregion
  
      #region Background
      BackgroundWorker worker = new BackgroundWorker();
  
      /// &lt;summary&gt;
      /// Executes the main find and replace operation.
      /// &lt;/summary&gt;
      /// &lt;param name="worker"&gt;The BackgroundWorker object.&lt;/param&gt;
      /// &lt;returns&gt;The number of files affected by the replace operation.&lt;/returns&gt;
      private int DoFindReplace(BackgroundWorker worker)
      {
          //Initialize the affected count variable
          int filesAffectedCount = 0;
  
          //Initialize the counter
          int counter = 0;
  
          //Get all XML files in the directory
          string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.txt");
  
          //Initialize total file count
          int totalFiles = filesInDirectory.GetLength(0);
  
          //Analyze each file in the directory
          foreach (string file in filesInDirectory)
          {
              //Perform find and replace operation
              if (FindAndReplace(file))
              {
                  //The file was changed so increment variable
                  filesAffectedCount++;
              }
  
              //Increment the counter
              counter++;
  
              //Report progress
              worker.ReportProgress((int)((counter / totalFiles) * 100.00));
          }
  
          //Return the total number of files changed
          return filesAffectedCount;
      }
      #endregion
  
      #region FindAndReplace
      /// &lt;summary&gt;
      /// Performs the find and replace operation on a file.
      /// &lt;/summary&gt;
      /// &lt;param name="file"&gt;The path of the file to operate on.&lt;/param&gt;
      /// &lt;returns&gt;A value indicating if the file has changed.&lt;/returns&gt;
      private bool FindAndReplace(string file)
      {
          //holds the content of the file
          string content = string.Empty;
  
          //Create a new object to read a file
          using (StreamReader sr = new StreamReader(file))
          {
              //Read the file into the string variable.
              content = sr.ReadToEnd();
          }
  
          //Get search text
          string searchText = GetSearchText(findWhatString);
  
          //Look for a match
          if (Regex.IsMatch(content, searchText))
          {
              //Replace the text
              string newText = Regex.Replace(content, searchText, replaceWithText);
  
              //Create a new object to write a file
              using (StreamWriter sw = new StreamWriter(file))
              {
                  //Write the updated file
                  sw.Write(newText);
              }
  
              //A match was found and replaced
              return true;
          }
  
          //No match found and replaced
          return false;
      }
      #endregion
  
      #region Various
      /// &lt;summary&gt;
      /// Gets the text to find based on the selected options.
      /// &lt;/summary&gt;
      /// &lt;param name="textToFind"&gt;The text to find in the file.&lt;/param&gt;
      /// &lt;returns&gt;The text to search for.&lt;/returns&gt;
      private string GetSearchText(string textToFind)
      {
          //Copy the text to find into the search text variable
          //Make the text regex safe
          string searchText = Regex.Escape(findWhatString);
  
          return searchText;
      }
      /// &lt;summary&gt;
      /// Sets the properties of the controls prior to beginning the download.
      /// &lt;/summary&gt;
      private void InitializeProcess()
      {
          //Get sources
          outputDirectory = txtDirectory.Text;
  
          //Set properties for controls affected when replacing
          statuslabel.Text = "Working...";
          progbar.Value = 0;
          progbar.Visible = true;
          btnprocess.Enabled = false;
          btncancel.Enabled = true;
  
          //Begin downloading files in background
          backgroundWorker.RunWorkerAsync();
      }
  
      /// &lt;summary&gt;
      /// Sets the properties of the controls after the download has completed.
      /// &lt;/summary&gt;
      private void DeinitializeProcess()
      {
          //Set properties for controls affected when operating
          statuslabel.Text = "Ready";
          progbar.Visible = false;
          btnprocess.Enabled = true;
          btncancel.Enabled = false;
      }
  
      /// &lt;summary&gt;
      /// Displays the directory browser dialog.
      /// &lt;/summary&gt;
      private void BrowseDirectory()
      {
          //Create a new folder browser object
          FolderBrowserDialog browser = new FolderBrowserDialog();
  
          //Show the dialog
          if (browser.ShowDialog(this) == DialogResult.OK)
          {
              //Set the selected path
              txtDirectory.Text = browser.SelectedPath;
          }
      }
  
      /// &lt;summary&gt;
      /// Validates that the user input is complete.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;A value indicating if the user input is complete.&lt;/returns&gt;
      private bool InputIsValid()
      {
          //Set the error flag to false
          bool isError = false;
  
          //Clear all errors
          errorProvider.Clear();
  
          //Validate the directory name
          if (string.IsNullOrEmpty(txtDirectory.Text))
          {
              errorProvider.SetError(txtDirectory, "This is a required field.");
              isError = true;
          }
          else
          {
              //check to make sure the directory is valid
              if (Directory.Exists(txtDirectory.Text) == false)
              {
                  errorProvider.SetError(txtDirectory, "The selected directory does not exist.");
                  isError = true;
              }
          }
  
          //Return a value indicating if the input is valid
          if (isError)
              return false;
          else
              return true;
      }
  
      #endregion
  
      #region Events
      private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
      {
          //Create a work object and initialize
          BackgroundWorker worker = sender as BackgroundWorker;
  
          //Run the find and replace operation and store total files affected in the result property
          e.Result = (int)DoFindReplace(worker);
      }
  
      private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
          //Update the prog bar
          progbar.Value = e.ProgressPercentage;
      }
  
      private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
          //The background operation is done
          DeinitializeProcess();
  
          //Perform final operations
          if (e.Error != null)
              MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
          else if (e.Cancelled)
              MessageBox.Show(this, "The operation was ended by the user.", "Cancelled.", MessageBoxButtons.OK, MessageBoxIcon.Error);
          else
              MessageBox.Show(this, string.Format("{0} files were updated by the operation.", e.Result.ToString()), "Replace Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
  
      }
      public DIPform()
      {
          InitializeComponent();
      }
  
      private void DIPform_Load(object sender, EventArgs e)
      {
  
      }
  
      private void btnprocess_Click(object sender, EventArgs e)
      {
          //Verify input is ok
          if (InputIsValid())
              InitializeProcess();
      }
  
      private void btncancel_Click(object sender, EventArgs e)
      {
  
      }
  
      //private void linkbrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
      // {
          //Select a directory to output files
      //    BrowseDirectory();
      //}
      private void linkbrowse_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
      {
          //Select a directory to output files
          BrowseDirectory();
      }
      #endregion
  
  
  
  }
  }
  </code></pre>