VB.net stopping a backgroundworker -
i want create button stop background worker , end process working on.
here sample backgroundworker code:
private sub button1_click(sender object, e eventargs) handles button1.click try if backgroundworker1.isbusy <> true backgroundworker1.runworkerasync() end if catch ex exception end try end sub private sub backgroundworker1_dowork(sender system.object, e system.componentmodel.doworkeventargs) handles backgroundworker1.dowork dim counter integer = 1 'updated code stop function---------------- backgroundworker1.workersupportscancellation = true if backgroundworker1.cancellationpending e.cancel = true progressbar1.value = 0 exit end if 'updated code stop function---------------- listbox1.items.add(counter) progressbar1.value = ((counter - 1) / limit) * 100 counter = counter + 1 loop while(counter <= 999999999999999999) end sub private sub backgroundworker1_progresschanged(sender system.object, e system.componentmodel.progresschangedeventargs) handles backgroundworker1.progresschanged try catch ex exception end try end sub private sub backgroundworker1_completed(sender system.object, e system.componentmodel.runworkercompletedeventargs) handles backgroundworker1.runworkercompleted try catch ex exception end try end sub private sub form1_load(sender object, e eventargs) handles mybase.load system.windows.forms.control.checkforillegalcrossthreadcalls = false end sub 'updated code stop function---------------- private sub stopbutton_click(sender object, e eventargs) handles stopbutton.click if backgroundworker1.isbusy if backgroundworker1.workersupportscancellation backgroundworker1.cancelasync() end if end if end sub 'updated code stop function----------------
i want reset loop , return progress bar 0% when stop backgroundworker.
is possible?
the code above has been updated , working fine.
i have added code inside loop:
backgroundworker1.workersupportscancellation = true if backgroundworker1.cancellationpending e.cancel = true progressbar1.value = 0 exit end if
i created button stops worker:
private sub stopbutton_click(sender object, e eventargs) handles stopbutton.click if backgroundworker1.isbusy if backgroundworker1.workersupportscancellation backgroundworker1.cancelasync() end if end if end sub
the backgroundworker class has method cancelasync()
need call cancel execution of bgw.
you need set backgroundworker.workersupportscancellation
property true , inside while loop need check cancellationpending
property wether value true
indicates call cancelasync()
method.
if cancellationpending
evaluates true, ( which should have done already ) call 1 of overloaded reportprogress()
(docu) methods set progressbar value desired value.
edit: should set cancel
property of doworkeventargs
true can check cancelled
property of runworkercompletedeventargs
inside runworkercompleted
event.
you shouldn not access controls lives in ui thread. better use progresschanged
(docu) event.
Comments
Post a Comment