使用BackgroundWorker处理多个操作 [英] Handling multiple operations using BackgroundWorker

查看:200
本文介绍了使用BackgroundWorker处理多个操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个winform上有一个DataGridView。我正在动态地添加DatagridViewButtonColumn的形式的加载方法,按钮名称为btnAction,文本显示为Process。



所以,网格中的每一行都将此过程按钮在最后一列。



在此按钮的单击事件上,我正在使用BackgroundWorker来调用一种进行某些计算的方法。计算结束后,我需要将该点击按钮的文本更新为网格中该行的已处理。现在,我如何处理这种情况? - >
用户单击多个Process按钮,我需要触发grid中所有相应行的计算。可以使用BackgroundWorker来处理,或者我需要使用线程这里?



请尽可能帮助代码片段。

解决方案

简单的答案是在运行时不能再次调用BackgroundWorker。如果你这样做,你会得到一个错误:


这个BackgroundWorker目前是
忙,不能运行多个任务
同时。


此问题已在StackOverflow上讨论过: C#这个BackgroundWorker当前正忙,不能同时运行多个任务



您需要做的是为后台工作人员请求的每个按钮或队列创建一个新的后台工作程序。排队的后台工作人员执行此处



无论你去哪个方式,你都需要小心,你写的代码都是线程安全的。


I have a DataGridView on a winform. I am dynamically adding DatagridViewButtonColumn in the load method of form with button name as btnAction and text displayed on it as "Process".

So, every row in the grid would have this Process button in the last column.

On click event of this button, I am using a BackgroundWorker to call a method which does some calculations. Once the calculations are over, I need to update that clicked button's text as "Processed" in that row in the grid. Now, how do i handle this scenario?--> The user clicks on multiple Process buttons and I need to trigger calculations for all the corresponding rows in the grid.Can it be handled using BackgroundWorker or I need to use threading here?

Please assist with code snippet if possible.

解决方案

The short answer is that the same BackgroundWorker cannot be called again while it is running. If you do that you will get an error:

This BackgroundWorker is currently busy and cannot run multiple tasks concurrently.

This issue has been discussed here on StackOverflow: C# This BackgroundWorker is currently busy and cannot run multiple tasks concurrently

What you need to do is either create a new background worker for each button or queue your background worker requests. There is a queued background worker implementation here.

Whichever way you go you will need to be careful that the code you write is all threadsafe.

这篇关于使用BackgroundWorker处理多个操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆