向后台工作者发送参数?
假设我想向后台工作者发送一个 int 参数,如何实现?
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
我知道这是worker.RunWorkerAsync();,我不明白如何在worker_DoWork中定义它应该采用int参数。
Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker_DoWork that it should take an int parameter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
你这样开始:
然后
You start it like this:
and then
尽管这是一个已经回答的问题,但我会留下另一个选项,IMO 更容易阅读:
在处理程序方法上:
Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
And on the handler method:
您可以像这样传递多个参数。
You can pass multiple arguments like this.
您可以使用
DoWorkEventArgs.Argument
属性。完整的示例(甚至使用 int 参数)可以在 Microsoft 的网站上找到:
You can use the
DoWorkEventArgs.Argument
property.A full example (even using an int argument) can be found on Microsoft's site:
查看 DoWorkEventArgs.Argument 属性:
Check out the DoWorkEventArgs.Argument Property:
如果您想传递多种类型的参数,您可以尝试一下,首先将它们全部添加到 Object 类型的数组中,然后将该对象传递给 RunWorkerAsync() 这是一个示例:
现在在后台工作程序的 doWork 方法中
you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :
Now in the doWork method of background worker
您需要 RunWorkerAsync(object) 方法和 DoWorkEventArgs.Argument 属性。
You need RunWorkerAsync(object) method and DoWorkEventArgs.Argument property.
您应该始终尝试使用具有具体类型的复合对象(使用复合设计模式)而不是对象类型列表。谁会记得这些物体到底是什么?稍后考虑维护代码......相反,尝试这样的事情:
然后:
然后:
You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:
And then:
and then: