Consider the following C# code:
private void SomeMethod()
{
IsBusy = true;
var bg = new BackgroundWorker();
bg.DoWork += (sender, e) =>
{
//do some work
};
bg.RunWorkerCompleted += (sender, e) =>
{
IsBusy = false;
};
bg.RunWorkerAsync();
}
I know VB.NET won't allow directly referencing DoWork
like that and you have to setup the worker by saying Private WithEvents Worker As BackgroundWorker
and explicitly handling the DoWork
event as follows:
Private Sub Worker_DoWork(
ByVal sender As Object,
ByVal e As DoWorkEventArgs) _
Handles Worker.DoWork
...
End Sub
However, I'd like to be able to implement a method like SomeMethod
from the C# example in VB.net. Likely this means wrapping the Backgroundworker in another class (which is something I want to do for dependency injection and unit testing anyway). I'm just not sure how to go about it in a simple, elegant way.
You can directly reference DoWork
just like in C# by using the AddHandler
keyword:
AddHandler bg.DoWork, Sub(sender, e)
DoSomething()
End Sub
AddHandler bg.RunWorkerCompleted, Sub(sender, e)
IsBusy = False
End Sub
bg.RunWorkerAsync()
Note that this only works on VB10, as earlier versions of VB don't support multi-statement lambdas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With