Is it possible to use multiple BackgroundWorker synchronously in WPF?

In my WPF application - I have a Listview with a Gridview inside. User can add files to this list.

The grid should allow me to have sufficiently rich "lines", each line shows the file name, additional details of the application and, most importantly, the progress bar. Each row in a gridview represents a data binding to a business object in the collection, and in particular, the object has the "Progress" property, which is associated with a progress bar.

I need to process each file, extract the data and send the data to the web service, and I would like to display the progress for each file in the corresponding execution line when working with the file collection.

First, I started with a simple loop containing processing logic that periodically updated the Progress field for each line and noted that the user interface was not updated very well.

Then I moved the processing logic in a loop to BackgroundWorker, which changed the field of the Progress business object, and also because the UI thread did not work so much - it was much more responsive.

However, due to the asynchronous nature of BackgroundWorker, it launched several BackgroundWorkers (one for each row) almost all at once when the loop was highlighted. All my progress indicators began to develop ...

What would be the best approach to limit it to only 2-3 BackgroundWorkers going at the same time? Or even leave it on one BackgroundWorker - and it does not start until the previous one is complete? How can I imagine a dependency so that, in fact, all BackgroundWorkers are synchronous?

+4
source share
2 answers

To do this, you can use the Task class, as in the example here

+7
source

If you really want only one to be executed at a time, there are several approaches. You can use the Task class and TaskScheduler, for example, @oleksii suggested in his answer, or you can send work items to a queue and have a background thread running one after another.

But if all you need to do is work in the most optimal way, depending on the current equipment your program is running on, then I would say that it is left to the default task scheduler. Just call StartNew in TaskFactory when you want to do the work for the grid line and leave the .NET planning.

If you have dependencies between tasks, you can use one of ContinueWith overloads to maintain order between tasks.

+2
source

All Articles