如何在vb.net中使用BackgroundWorker将代码包装在lambda表达式中?
考虑以下 C# 代码:
private void SomeMethod()
{
IsBusy = true;
var bg = new BackgroundWorker();
bg.DoWork += (sender, e) =>
{
//do some work
};
bg.RunWorkerCompleted += (sender, e) =>
{
IsBusy = false;
};
bg.RunWorkerAsync();
}
我知道 VB.NET 不允许像这样直接引用 DoWork
,并且您必须通过说 Private WithEvents Worker As BackgroundWorker
并显式地设置工作线程按如下方式处理 DoWork
事件:
Private Sub Worker_DoWork(
ByVal sender As Object,
ByVal e As DoWorkEventArgs) _
Handles Worker.DoWork
...
End Sub
但是,我希望能够从 VB.net 中的 C# 示例实现类似 SomeMethod
的方法。可能这意味着将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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以直接引用
DoWork
,就像在C#中一样,使用AddHandler
关键字:请注意,这仅适用于VB10,因为早期版本的VB不支持不支持多语句 lambda。
You can directly reference
DoWork
just like in C# by using theAddHandler
keyword:Note that this only works on VB10, as earlier versions of VB don't support multi-statement lambdas.
如果您使用的是 VB.NET 10(随 Visual Studio 2010 一起提供),则以下内容应该可以正常工作:
此处需要 VB.NET 10,因为早期版本的 VB.NET 不允许使用 lambda(匿名
Subs 即)跨越不止一行。
话虽这么说,您应该能够以 .NET Framework 的早期版本为目标,因为上面的代码与 CLR 版本 2 兼容。
If you're using VB.NET 10 (which comes with Visual Studio 2010), the following should work fine:
VB.NET 10 is required here because earlier versions of VB.NET did not permit lambdas (anonymous
Sub
s 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.