title: C# SynchronizingObject and Timer.Timer thread
body: <p>Hi i am trying to make the Elapsed event of the Timer.Timer class fire on my main thread.
  I am restricted to VS 2008, .net 3.5...
  In this post: 
  <a href="https://stackoverflow.com/questions/1435876/do-c-sharp-timers-elapse-on-a-separate-thread">Do C# Timers elapse on a separate thread?</a> 
  it is stated that using a SynchronizingObject will make the handler execute on the thread that owns the object.</p>
  
  <p>So I tried this:</p>
  
  <pre><code>class MyTimer
  {
    private readonly Timer timer;
  
    public MyTimer(ISynchronizeInvoke synchronizingObject)
    {
      Console.Out.WriteLine(Thread.CurrentThread.ManagedThreadId);
      timer = new Timer(1000);
      timer.SynchronizingObject = synchronizingObject;
      timer.Elapsed +=
        delegate
          {
            timer.Stop();
            Thread.Sleep(2000);
            Console.Out.WriteLine(Thread.CurrentThread.ManagedThreadId);
            timer.Start();
  
          };
      timer.Start();
    }
  }
  
  class Program
  {
    static void Main(string[] args)
    {
      ISynchronizeInvoke syncObject = new Control();
      var mytimer = new MyTimer(syncObject);
  
      Console.ReadKey();
    }
  }
  </code></pre>
  
  <p>But the output is: 1,4,4,4,4...</p>
  
  <p>Why is that? How do i make the Elapsed handler execute on the mainthread.</p>
  
  <p>I tried using <a href="https://stackoverflow.com/questions/1841345/synchronizingobject-for-an-event">SynchronizingObject for an event</a>
  but that didn't help either:</p>
  
  <pre><code>  public static ElapsedEventHandler Wrap(ElapsedEventHandler original, ISynchronizeInvoke synchronizingObject) 
    {
      return (sender, args) =&gt;
      {
        if (synchronizingObject.InvokeRequired)
        {
          synchronizingObject.Invoke(original, new object[] { sender, args });
        }
        else
        {
          original(sender, args);
        }
      };
    }
  </code></pre>
  
  <p>and: </p>
  
  <pre><code>timer.Elapsed += Wrap(
        delegate
          {
            timer.Stop();
            Thread.Sleep(200);
            Console.Out.WriteLine(Thread.CurrentThread.ManagedThreadId);
            timer.Start();
          }, 
          synchronizingObject);
  </code></pre>
  
  <p>But still no success... everytime InvokeRequired is false...</p>
  
  <p>forcing debug into the invoke causes a invalidoperation: "Invoke or BeginInvoke cannot be called on a control until the window handle has been created." </p>
  
  <p>last resort would be to look into:
  <a href="http://www.codeproject.com/Articles/12082/A-DelegateQueue-Class?msg=3655119#xx3655119xx" rel="nofollow noreferrer">http://www.codeproject.com/Articles/12082/A-DelegateQueue-Class?msg=3655119#xx3655119xx</a>
  but is that really necessary? or is there some simpler solution?</p>