在BackgroundWorker中同步工作
我的应用程序在多个文件上独立执行耗时的工作。 我创建了一个BackgroundWorker来将工作传递给每个文件,但看起来BackgroundWorker只能执行异步工作。 是否可以与其一起执行多个异步任务,或者是否有类似的对象用于执行同步操作?
My application performs time consuming work independently on several files. I created a BackgroundWorker to pass the work off to on each file, but it appears the backgroundworker is only capable of performing asynchronous work. Is it possible to do several asynchronous tasks in unison with it, or is there a similar object for performing synchronous operations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
后台工作人员通常用于更新 UI 和/或传递工作,以便在长时间运行的进程发生时不会冻结 UI。 这意味着您“传递”后台工作进程“文件工作”,然后使用回调来更新 UI(通常),在此期间您的应用程序保持响应。
如果这些项目是独立的,那么您可能需要假脱机几个线程来分割工作。 再说一次,如果我理解正确的话。 如果我是,那么您可能需要查看 Jon Skeet 的线程文章。
The background worker is usually used to update the UI and/or to pass off work so you don't freeze the UI when a long running process takes place. This means that you "pass" the background worker process the "file work" and then use a callback to update the UI(usually) all during which your APP remains responsive.
If the items are independent then you might want to spool up a few threads to split the work. Again, if I am understanding you correctly. If I am then you might want to look at Jon Skeet's threading article.
虽然您可以使用BackgroundWorker,但我认为您应该简单地分出几个线程来完成这项工作。 一个线程(可能是主线程)将创建并启动这些工作线程,然后对所有工作线程执行 Join 以等待处理完成。
或者,查看 .Net 的并行扩展(如果您使用的是 .Net 3.5)。 该库中的 Task 对象可能非常适合您的情况。
While you can use the BackgroundWorker, I think you should simply spin off a few threads to do the work. One thread (probably the main thread) will create and start these worker threads and then perform a Join on all the workers in order to wait for processing to complete.
Alternatively, have a look a the Parallel Extensions for .Net if you are using .Net 3.5. The Task object from that library is probably perfect for your situation.
您可以通过在代码中创建多个BackgroundWorker 对象来执行多项异步任务。 我们创建了一个JobPool类,它创建了多个BackgroundWorker对象来运行,这样我们就可以控制任意时刻运行的总数。 但如果只有几个文件,您将处理这将是多余的。
You can do multiple aynchronous tasks by creating more then one BackgroundWorker object in your code. We created a JobPool class that created a number of BackgroundWorker objects to run so that we could control the total number running at any one time. But if there are just a few files you will be processing this wouldbe overkill.