title: C# Multi Thread Design Example
body: <p>I am relatively new to C#/.Net. I'm developing a desktop application that requires multi threading. I came up with the following pattern below as a base. I was wondering if anyone could point out how to make it better in terms of coding, being thread safe, and being efficient.</p>
  
  <p>Hopefully this makes some sense.</p>
  
  <hr>
  
  <pre><code>public abstract class ThreadManagerBase
  {
      // static class variables
  
      private static ThreadManagerBase instance = null;
      private static BackgroundWorker thread = null;
      private static ProgressBarUIForm progress = null;
  
      /// &lt;summary&gt;
      /// Create a new instance of this class. The internals are left to the derived class to figure out.
      /// Only one instance of this can run at any time. There should only be the main thread and this thread.
      /// &lt;/summary&gt;
      public abstract static ThreadManagerBase NewInstance();
  
      /// &lt;summary&gt;
      /// Clears the instance.
      /// &lt;/summary&gt;
      public static void ClearInstance()
      {
          instance = null;
      }
  
      /// &lt;summary&gt;
      /// Initializes the background worker with some presets.
      /// Displays progress bar.
      /// &lt;/summary&gt;
      private abstract static void InitializeThread()
      {
          thread = new BackgroundWorker();
  
          thread.WorkerReportsProgress = true;
          thread.WorkerSupportsCancellation = true;
  
          thread.DoWork += new DoWorkEventHandler(thread_DoWork);
          thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(thread_RunWorkerCompleted);
          thread.ProgressChanged += new ProgressChangedEventHandler(thread_ProgressChanged);
  
          thread.RunWorkerAsync();
  
          progress = new ProgressBarUIForm();
  
          progress.EnableCancelButton = true;
  
          progress.UserCanceled += new EventHandlerCancelClicked(progress_UserCanceled);
  
          progress.ShowDialog();
  
          thread.Dispose();
  
          thread = null;
      }
  
      private static void progress_UserCanceled(bool userCanceled)
      {
          thread.CancelAsync();
      }
  
      private static void thread_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
          progress.SetProgressLevel = e.ProgressPercentage;
          progress.SetProgressMessage = e.UserState.ToString();
      }
  
      private static void thread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
          progress.Close();
  
          progress = null;
      }
  
      private static void thread_DoWork(object sender, DoWorkEventArgs e)
      {
          ProcessWork();
      }
  
      private abstract static void ProcessWork()
      {
          // do actuall stuff here.
          // the derived classes will take care of the plumbing.
      }
  }
  </code></pre>