How should threads update global data in the main program?

I am revising an old thread .

I want to start a bunch of threads, each of which performs the same task, and I know in main () when everyone finishes, and if it was successful or unsuccessful.

The proposed solution was to use ConcurrentQueue, but other posts recommended using the BackgroundWorker Class or thread pool.

Is there a definitive answer?

Again, all threads execute the same code and have a pass / fail result. I want to start more than there are threads available, and as soon as one thread ends, I started another option - I want tehm to maximize the strength of remote systems (instead of stressing my local PC with too many threads, I will need experiment to determine the optimal number of threads).

VB.NET is for a specific answer, but general thread advice is also welcome.

+4
source share
4 answers

BackgroundWorker is a very easy way to manage threads. It makes it easy to report progress in the user interface. I don’t think there is a final answer, but BackgroundWorker is designed for this purpose - launching background tasks that update the user interface as they progress. Here is an example of how to do this .

+5
source

Josh is how I go.

Create as many new background workers as you need, connect to intercept their “finished” event (I forgot the exact name), and when these events return to the main application stream, save the results in a collection / list / somesort array.

Things can be interesting if you really need to combine threads so that you don't just create a ton of threads that can cause a lot of context shuffling. Instead, you want to have a pool, say 2x (the number of processors in the machine), and as each desktop ends, there is a queue for another task in it.

+1
source

It depends. In a Windows Forms application, I would go with BackgroundWorker because it is very easy to set up and use, and it saves me many headaches that look for the wrong cross-stream errors.

But you should know that BackgroundWorker only works correctly in an environment where there is a user interface stream and message loop. Thus, it will not work in a console application, for example.

In this case, you should use another solution, Thread , ThreadPool or some kind of structure.

+1
source

I agree with the suggestions about BackgroundWorker. However, if you need to access COM objects from background streams, do not use BackgroundWorker, but create your own streaming engine and use the MTA STA model as needed.

+1
source

Source: https://habr.com/ru/post/1344216/


All Articles