带参数的BackgroundWorker基本用法
我想要在后台线程中执行的进程密集型方法调用如下所示:
object.Method(paramObj, paramObj2);
所有这三个对象都是我创建的。现在,从我看到的最初示例来看,您可以将一个对象传递到后台工作者的 DoWork 方法中。但是,如果我需要向该对象传递其他参数(就像我在这里所做的那样),我应该如何去做呢?我可以将其包装在一个对象中并完成它,但我认为获取其他人对此的输入是明智的。
My process intensive method call that I want to perform in a background thread looks like this:
object.Method(paramObj, paramObj2);
All three of these objects are ones I have created. Now, from the initial examples I have seen, you can pass an object into a backgroundworker's DoWork method. But how should I go about doing this if I need to pass additional parameters to that object, like I'm doing here? I could wrap this in a single object and be done with it, but I thought it would be smart to get someone else's input on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将任何对象传递到 RunWorkerAsync 调用的对象参数中,然后从 DoWork 事件中检索参数。您还可以使用 DoWorkEventArgs 中的 Result 变量将参数从 DoWork 事件传递到 RunWorkerCompleted 事件。
You can pass any object into the object argument of the RunWorkerAsync call, and then retrieve the arguments from within the DoWork event. You can also pass arguments from the DoWork event to the RunWorkerCompleted event using the Result variable in the DoWorkEventArgs.
我想到的最简单的方法是为您拥有的每个对象创建一个具有属性的类,然后传递该属性。
然后在 DoWork 中您只需执行以下操作:
The simplest way that comes to my mind would be creating a class with a property for every object you have, and passing that.
then in the DoWork you simply do something like:
您可以在 DoWork 的 lambda 中捕获它们:
e.Argument
(即传递给BackgroundWorker.RunWorkerAsync()
的状态值或对象)可以是 3 个中的 1 个,但是它是 System.Object 类型并且需要装箱。直接在 lambda 中传递所有参数可为您提供所有参数的完全类型安全性,无需装箱或转换。You can capture them in a lambda for DoWork:
e.Argument
(i.e. the state value or object passed toBackgroundWorker.RunWorkerAsync()
) could be 1 of the 3, but it is of typeSystem.Object
and would require boxing. Passing all of the parameters directly in the lambda gives you full type-safety on all of the parameters without any need for boxing or casting.您可以将对象传递到BackgroundWorker.RunWorkerAsync() 方法中。您应该将两个 paramObjs 包装到一个对象中(您可以使用数组、元组或您编写的其他复合类)并将其作为参数传递到 RunWorkerAsync() 中。
然后,当引发 DoWork 事件时,您可以通过查看事件处理程序的 DoWorkEventArgs 参数的 Argument 属性来检索该值。
有关完整示例,请查看 MSDN:http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=VS.90%29.aspx
You can pass an Object into the BackgroundWorker.RunWorkerAsync() method. You should wrap your two paramObjs into one Object (you could use an array, a tuple, or some other composite class that you would write) and pass that as the argument into RunWorkerAsync().
Then, when your DoWork event is raised, you can retrieve this values by looking at the Argument property of the DoWorkEventArgs parameter of the event handler.
For a complete example, check out on MSDN: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker%28v=VS.90%29.aspx