.net - BackgroundWorker threading issue -


i'm getting infamous "cross-thread operation not valid" exception when trying implement simple backgroundworker. i've spent hours reading can find on subject, including many related questions on so, i'm not getting it.

i have simple winform has dowork() method:

  1. it takes delegate representing work done.
  2. it creates backgroundworker , assigns delegate dowork event.
  3. it calls runworkerasync().

the function invoked runworkercompleted() tries update label on form, throws cross-thread exception.

public class myform      public sub dowork(worktodo doworkeventhandler)         dim worker new backgroundworker()         worker.workerreportsprogress = true         worker.workersupportscancellation = true         addhandler worker.dowork, worktodo         addhandler worker.runworkercompleted, addressof workercompleted         worker.runworkerasync()     end sub      private sub workercompleted(byval sender object, byval e runworkercompletedeventargs)         resultlabel.text = "done!" ' exception thrown here     end sub  end class 

so looks workercompleted running on background thread. close working solution, or failing grasp fundamentals?

update: mysterious fix

i discovered "fix" dumb luck. have further application. part of vsto excel add-in. instantiating form in ribbon load event , calling show() when button clicked. raised exception.

private sub ribbon1load(byval sender system.object, byval e ribbonuieventargs) handles mybase.load     mprocessing = new myform() end sub   private sub button1click(sender system.object, e ribboncontroleventargs) handles button1.click     mprocessing.show()     mprocessing.dowork(addressof updatedata) end sub 

moving mprocessing = new myform() click handler eliminates exception. working well. moved code , forth several times , confident in problem/solution.

the runworkercompleted event run on same thread backgroundworker (ui thread) doubt that's problem here. suspect error occurring during dowork method , being thrown once hit ui thread. docs state:

your runworkercompleted event handler should check asynccompletedeventargs.error , asynccompletedeventargs.cancelled properties before accessing runworkercompletedeventargs.result property. if exception raised or if operation canceled, accessing runworkercompletedeventargs.result property raises exception.

on off chance are hitting problem runworkercompleted event not running on ui thread can invoke ui update run on correct thread using invoke e.g.

resultlabel.invoke(sub() resultlabel.text = "done!") 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -