Handling multiple operations using BackgroundWorker

北城余情 提交于 2019-12-24 04:55:14

问题


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.


回答1:


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: 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.




回答2:


I had a similar scenario while using a BackgroundWorker process.

The following Codeproject article helped me a lot to get around it.

http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx




回答3:


http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.runworkercompleted(v=vs.85).aspx

Will show you how to handle the backgroundworker.runworkercompleted event which will let you do something once the backgroundworker is done (whether by error or completion you will have to check).



来源:https://stackoverflow.com/questions/6306503/handling-multiple-operations-using-backgroundworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!