2

I have a BackgroundWorker in a vb.net program that is doing a lengthy data import routine. I want to modify its RunWorkerAsync method so that it fires a custom event on completion of the method. (So that a method in an automated process can respond to the event and resume its work). In a sense I want to 'extend' the RunWorkerAsync method to add an extra line of code--but I can't 'see' the code in the method (to just add the line raising the event) because BackgroundWorker is an MSDN class from Microsoft.

The only solution that I can think of is to 'wrap' the background worker class in a wrapper that calls the .RunWorkerAsync method and then raises the event.

Public sub wrapperMethod()
    myBackgroundWorker.RunWorkerAsync()
    raise customEvent
end sub

Is there a design pattern that I might use? An easy way to address this with the .net language?

PS: Unfortunately, I'm automating some clanking legacy software and backgroundworker is used in many locations, so wrapping the backgroundworker will be a bit of work and may open bugs.

bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • can you override the base "RunWorkerAsync" method with your own, that raises your own event as well as calling MyBase.RunWorkerAsync - or if the "RunWorkerAsync" method isn't marked as Overridable use Shadows instead. See here for examples: http://stackoverflow.com/questions/463209/shadows-vs-overrides-in-vb-net – Jeremy Thompson Nov 16 '11 at 23:09
  • I don't think either will work. A shadow would hide the .RunWorkerAsync() method (so I would not be able to start a background thread). A child class with an override method will either keep the parent's RunWorkerAsync() method as is (which would not help) or replace/hide the method (which would again mean I would not be able to easily create a background thread) – bernie2436 Nov 17 '11 at 00:12

1 Answers1

7

"In a sense I want to 'extend' the RunWorkerAsync method to add an extra line of code"

Tap into the RunWorkerComplete event and use that as your "raise customEvent", here is an example on MSDN:

Background Worker RunWorkerCompleted event

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321