1 Replies - 5534 Views - Last Post: 29 June 2009 - 05:11 PM Rate Topic: -----

#1 creatiive   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 22-June 09

BackgroundWorker cross-thread error

Posted 22 June 2009 - 08:36 AM


I have a main form that opens a dialog. My dialog starts a timer that periodically queries a web service for information and updates some dialog GUI aspects. I also have a BackgroundWorker set up in the dialog. The code in DoWork goes off and runs a time consuming webmethod from the webservice. The ThreadFinished method stops the timer on the dialog, removes some event handlers and then sets the dialog result to OK (which in turn closes the dialog).

This appears to work fine. However, if i put in any breakpoints anywhere in this code and try and step through some areas, nomatter where i breakpoint it causes a cross-thread communication expection to occur in the Dispose method which gets called when the dialog closes.

I do not know why this only happens when i breakpoint but my best guess is that it doesnt like me closing the dialog in the RunWorkerCompleted event? Could someone point me in the right direction with this? Any help would be greatly appriciated.


 public myDialog() {
	BackgroundWorker m_Worker = new BackgroundWorker();
	m_Worker.DoWork += new DoWorkEventHandler(DoWork);
	m_Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ThreadFinished);
public void DoWork(object sender, DoWorkEventArgs e) {
public void ThreadFinished(object sender, RunWorkerCompletedEventArgs e) {
	 this._myTimer.Elapsed -= new System.Timers.ElapsedEventHandler(TickHandler);
	 this.DialogResult = DialogResult.OK;

Is This A Good Question/Topic? 0
  • +

Replies To: BackgroundWorker cross-thread error

#2 masteryee   User is offline

  • D.I.C Regular

Reputation: 40
  • View blog
  • Posts: 271
  • Joined: 16-May 09

Re: BackgroundWorker cross-thread error

Posted 29 June 2009 - 05:11 PM

Did you ever figure this out? What's the full error you are receiving? The only thing I can think of is that when you're in debug mode and you have a breakpoint, your timer and backgroundworker code may still be running while you're busy stepping through your dialog's main thread code. If your timer and/or backgroundworker are accessing controls without calling Invoke() on the control, then you'll experience a cross-thread exception. My guess is that when you wrote and tested your code, your tests never raised the TickHandler method, and you're trying to update a control in the TickHandler method without first calling Invoke().
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1