.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:
- it takes delegate representing work done.
- it creates
backgroundworker
, assigns delegatedowork
event. - 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
Post a Comment