Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap code in a lambda expression using a BackgroundWorker in vb.net?

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.

like image 356
Matt Avatar asked Dec 28 '22 18:12

Matt


1 Answers

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.

like image 76
Sven Avatar answered Jan 03 '23 04:01

Sven