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
DoWorkjust like in C# by using theAddHandlerkeyword:Note that this only works on VB10, as earlier versions of VB don’t support multi-statement lambdas.