title: Trouble with timers and threads
body: <p>I'm a learn-by-example C# coder who isn't very advanced, which is why this problem is completely stumping me regardless of the amount of information on the internet.</p>
  
  <p>I'm essentially creating a program that is, on a timer, repeatedly polling a website to get some information.  During this process, a WebBrowser control is created to navigate to the information (needed for authentication).  The program runs this series of events at startup, then using a System.Timers.Timer set to every 10 minutes (less for debugging of course) to do that same series of events yet when my Timer.Elapsed event triggers that process, I get a:</p>
  
  <p><strong>ThreadStateException</strong> with the description as <em>ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment.</em></p>
  
  <p>Here is a slimmed down version of my program.</p>
  
  <pre><code>private void Form1_Load(object sender, EventArgs e)
          {
              GetDataFromWebBrowser();
              Set_Auto_Refresh_Timer();
          }
  
  private void Set_Auto_Refresh_Timer()
          {
              System.Timers.Timer TimerRefresh = new System.Timers.Timer(10000);
              TimerRefresh.Elapsed += new System.Timers.ElapsedEventHandler(TimerRefresh_Elapsed);
              TimerRefresh.AutoReset = true;
              TimerRefresh.Start();
          }    
  
  private void TimerRefresh_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
          {
              GetDataFromWebBrowser();
          }
  
  private void GetDataFromWebBrowser()
          {
              WebBrowser wb = new WebBrowser();  &lt;--This is where the error is thrown.
  
              ...get web data...
  
          }
  </code></pre>
  
  <p>I think I got enough code in there to paint the picture.  As you can see, when it gets to creating another WebBrowser, it throws the error.</p>
  
  <p>I'm really stumped and I'm just starting to scrape the surface on Threading which is probably why I'm so stumped.  </p>
  
  <p>//Solution for me/
  I ended up moving the WebBrowser creation out of the method as well as making it static to just reuse the WebBrowser control.  I also swapped my System.Timers.Timer to System.Threading.Timer.  Seemed to fix the problem.</p>