title: WPF Thread Delay
body: <p>I have a method which I call in a new task with</p>
  
  <pre><code>// get the dispatcher for the UI thread
  var uiDispatcher = Dispatcher.CurrentDispatcher;
  Task.Factory.StartNew(() =&gt; BackgroundThreadProc(uiDispatcher));
  </code></pre>
  
  <p>In the method <code>BackgroundThreadProc()</code> I need a delay of few seconds. I tried it with the DispatcherTimer and the task.delay function but it didn't work. The only thing which worked was the <code>System.Threading.Thread.Sleep(1)</code> but I think the <code>Thread.Sleep()</code> function isn't the best solution.</p>
  
  <p>This is my function:</p>
  
  <pre><code>public void BackgroundThreadProc(Dispatcher uiDispatcher)
  {
      for (var i = 0; i &lt; 100; i++)
      {
          var task = Task.Delay(1000).ContinueWith(t =&gt;
          {
              // create object
              var animal = new Animal { Name = "test" + i };
              uiDispatcher.Invoke(new Action(() =&gt; log(animal)));
          });
      }
  }
  </code></pre>
  
  <p>As I found out it didn't work because the DispatcherTimer is running in the UI thread. How I can accomplish the delay in the function which is in a other thread than the UI thread?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Now I tried it with the timer:</p>
  
  <pre><code>   public void BackgroundThreadProc(Dispatcher uiDispatcher)
      {
          for (var i = 0; i &lt; 100; i++)
          {
              var _delayTimer = new System.Timers.Timer();
              _delayTimer.Interval = 1000;
              //_delayTimer.Enabled = true;
              _delayTimer.Elapsed += delegate
              {
                  var animal = new Animal { Name = "test" + i };
                  uiDispatcher.Invoke(new Action(() =&gt; log(animal)));
                  _delayTimer.Stop();
              };
              _delayTimer.Start();
          }
      }
  </code></pre>