开发者

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

开发者 https://www.devze.com 2023-03-15 01:13 出处:网络
Consider the following C# code: private void SomeMethod() { IsBusy = true; var bg = new BackgroundWorker();

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 A开发者_如何学Gos 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're using VB.NET 10 (which comes with Visual Studio 2010), the following should work fine:

Dim bg = New BackgroundWorker()
AddHandler bg.DoWork,
    Sub()
        DoSomething()
    End Sub
AddHandler bg.RunWorkerCompleted,
    Sub()
        IsBusy = False
    End Sub
bg.RunWorkerAsync()

VB.NET 10 is required here because earlier versions of VB.NET did not permit lambdas (anonymous Subs that is) that span more than one line.

That being said, you should be able to target earlier versions of the .NET Framework, because the above code is compatible with version 2 of the CLR.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号