title: How to make a C# timer that fires events in the main thread?
body: <p>Long story short, I need a precise timer in .Net - with prescision in milliseconds - meaning, if I tell it to fire an event when 10ms passes, it must do so, +-1ms. The built-in .Net Timer class has a precision of +-16ms it seems, which is unacceptable for my application.</p>
  
  <p>I found this article <a href="http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer">http://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer</a> which provides a code for a timer that is exactly what I need (even more - that has precision in microseconds). </p>
  
  <p>However, problem is, the OnTimer equivalent seems to be executed in another thread. So, if I add some code that does, say:</p>
  
  <pre><code>label1.Text = "Hello World";
  </code></pre>
  
  <p>I will get an exception, and thus I will have to actually write it like this:</p>
  
  <pre><code>Invoke( new MethodInvoker(() =&gt;{label1.Text = "Hello World";}));
  </code></pre>
  
  <p>This is, from what I understand, because the OnTimer event is fired from the timer's thread - where time is passed until enough has passed to be over the Interval, and then next OnTimer event is fired. The .Net Timer does not have such a problem - in OnTimer of the .Net Timer, I can freely modify controls's members.</p>
  
  <p>Question: What should I change so that my timer will run it's OnTimer event in the main thread? Is adding "Invoke" the only choice?</p>