后台工作者
如果我有一组操作,我想根据特定条件在后台工作人员中运行,并且我有 10 个条件,例如
if(a)
BackgroundWorker doA = new backgroundworker()
if(b)
BackgroundWorker doB = new backgroundworker()
if(c)
BackgroundWorker doC = new backgroundworker()
if(d)
BackgroundWorker doD = new backgroundworker()
...
...
每个后台工作人员都需要 dowork、runworkercompleted 等......无论如何都可以避免这种情况所以它使代码不那么混乱/混乱,因为其中一些方法可能相当大?
谢谢
If i have a set of actions i want to run in a background worker based on a certain condition and i have 10 conditions, for example
if(a)
BackgroundWorker doA = new backgroundworker()
if(b)
BackgroundWorker doB = new backgroundworker()
if(c)
BackgroundWorker doC = new backgroundworker()
if(d)
BackgroundWorker doD = new backgroundworker()
...
...
each of those background workers will require a dowork, runworkercompleted etc.... is there anyway to avoid that so it makes the code less messy/clutered as some of those methods might be quite big?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用
任务
来自System.Threading.Tasks
命名空间,它非常简单且易于使用。要启动任务,您只需使用:
Task.Factory.StartNew()
传递方法或 lambda 表达式作为参数。你会得到一个Task
对象,你可以用它来继续操作、获取结果等。You should use
Task
from theSystem.Threading.Tasks
namespace instead, it's very simple and easy to use.To start a task, you can simply use:
Task.Factory.StartNew()
passing a method or a lambda expression as a parameter. you get back aTask
object that you can use for continuation, getting the result back, etc.您可以考虑使用单个后台工作程序并向其传递一个参数。在 DoWork 方法中使用此参数,您可以确定要工作的代码块。检查此线程
向后台工作者发送参数?
You can consider using a single backgroundworker and passing an argument to it.Using this argument in the DoWork method you can determine which block of code to work.Check this thread
Sending Arguments To Background Worker?
为什么不将需要评估的对象传递给BackgroundWorker,然后BackgroundWorker可以使用它来确定要做什么?
Why don't you pass in the object that needs evaluating to the BackgroundWorker and the BackgroundWorker can use it to determine what to do?