Monday, September 20, 2010

InvalidOperationException During Debugging

I got InvalidOperationException when debugging my code:


System.InvalidOperationException was unhandled
  Message="Cross-thread operation not valid: Control 'StatusBar' accessed from a thread other than the thread it was created on."
  Source="System.Windows.Forms"
The exception only occur on debugging mode, no problem at all at release mode

After quick and dirty investigation, this code is the one causing exception:
// Activate Watcher Thread
watcherThread  = new Thread(new ThreadStart(watcher));
watcherThread.IsBackground = true;
watcherThread.Start();

And this is the function
//------------------------------------//
//  WATCHER - Background Threads   //
//------------------------------------//
#region Watcher
private void Watcher()
{
 long lngTimeoutTick = DateTime.Now.AddSeconds(10).Ticks;
 while (true)
 {
  if (watchThreadActive)
  {
   // ...
  }
  if (DateTime.Now.Ticks > lngTimeoutTick)
  {
   this.ShowInputStatus();
   // ...
   lngTimeoutTick = DateTime.Now.AddSeconds(10).Ticks;
   this.ShowStatBar("");
  }
  System.Threading.Thread.Sleep(watcherWaitTime * 1000);
 }
}

#endregion Watcher
one of the lines in the function must be the actual 'culprit', but the (also quick and dirty) workaround is to commented out the 'blamed' code during debugging
// Activate Watcher Thread
//watcherThread  = new Thread(new ThreadStart(watcher));
//watcherThread.IsBackground = true;
//watcherThread.Start();
Don't forget to uncomment selected lines after debugging. We don't want to have 'production issue' later