title: Waiting the main thread to stop until a task is processed by an async thread
body: <p>Lets say we have a following program where in its Start method, it delegates some long running task to another thread. When the Stop method is called, i need to make sure that worker thread completes executing the current task and does not leave it in the middle of it. If it has already completed the task and is in sleep state, then it can stop immidiately.</p>
  
  <p>Please guide me on how should I do it.</p>
  
  <pre><code>    static int itemsProcessed = 0;
      static Thread worker;
      static void Start()
      {
          var ts = new ThreadStart(Run);
          worker = new Thread(ts);
          worker.Start();
      }
  
      static void Stop()
      {
          //wait until the 'worker' completes processing the current item.
          Console.WriteLine("{0} Items Processed", itemsProcessed);
      }
  
      static void Run(object state)
      {
          while (true)
          {
              ALongRunningTask();
              itemsProcessed++;
              Thread.Sleep(1000);
          }
      }
  </code></pre>