B
B
Bur-Burito2017-02-15 04:44:09
C++ / C#
Bur-Burito, 2017-02-15 04:44:09

Is there a way in C# to wait for all tasks that have been added to the execution queue to the thread pool to complete?

There is a method that, under certain conditions, recursively adds itself to the execution queue in the ThreadPool. Is it possible to somehow shade the end of the execution of the last task in this queue?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Axian Ltd., 2017-02-15
@AxianLTD

Apparently the documentation is not fashionable to read now ( https://msdn.microsoft.com/en-us/library/system.th...
GetAvailableThreads(Int32, Int32) - Retrieves the difference between the maximum number of thread pool threads returned by the GetMaxThreads method, and the number currently active
.

M
MonkAlex, 2017-02-15
@MonkAlex

In the abstract, it's impossible.
And so - what prevents you from doing this in the same method that queues? You do ContinueWith and write processing on "after execution", with processing in the necessary form.

A
Artem, 2017-02-15
@devspec

Maybe do something like this?

int working_tasks = 0;
ManualResetEventSlim pre = new ManualResetEventSlim(false);

// здесь запуск тасков
// в каждом таске (в начале) ставим working_tasks = Interlocked.Increment(working_tasks);
// в конце - if(Interlocked.Read(working_tasks) == 0) { pre.Set(); }

pre.Wait();

// здесь то, что должно выполняться после выполнения всех тасков

Thus, at the beginning of the task execution, we increase a certain variable by 1, and at the end - decrease it by 1. If all tasks are completed (the variable is equal to 0), we set the reset-event flag - and the code after pre.Wait () starts executing.
I'm not sure about the correctness (I wrote from memory), but the idea seems to be working. Correct me if I'm wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question