Reputation: 353
Given the code below what is the most elegant way to notify consumers when all tasks have run to completion without blocking the thread? Currently I have a solution using a counter which is incremented before the Execute(action)
and decremented after the Continuation()
and LogException()
. If the counter is zero then it is safe to assume that no more tasks are being processed.
Upvotes: 0
Views: 58
Reputation: 203844
First off, don't use the Task
constructor at all. If you want to run a delegate in a thread pool thread, use Task.Run
. Next, don't use ContinueWith
, use await
to add continuations to tasks. It's much easier to write correct code that way, particularly with respect to proper error handling. Your code is most effectively written as:
try
{
await Task.Run(() => Execute(action));
Continuation();
}
catch(Exception e)
{
LogExceptions(e)
}
finally
{
CustomLogging();
}
Upvotes: 3