Is there a way to globally WaitAll() for all tasks created by a process?

Is there a way to globally WaitAll() for all tasks created by a process?

By : user3042262
Date : November 27 2020, 05:23 PM
seems to work fine You could create a task aggregator, a task that completes when all observed tasks are completed. It would be a functionally equivalent version of Task.WhenAll, but much more lightweight since only the number of incomplete tasks would be stored, not the tasks themselves. Here is an implementation of this idea:
code :
public class TaskAggregator
    private int _activeCount = 0;
    private int _isAddingCompleted = 0;
    private TaskCompletionSource<bool> _tcs = new TaskCompletionSource<bool>();

    public Task Task { get => _tcs.Task; }

    public int ActiveCount
        get => Interlocked.CompareExchange(ref _activeCount, 0, 0);

    public bool IsAddingCompleted
        get => Interlocked.CompareExchange(ref _isAddingCompleted, 0, 0) != 0;

    public void Add(Task task)
        Interlocked.Increment(ref _activeCount);
        task.ContinueWith(_ =>
            int localActiveCount = Interlocked.Decrement(ref _activeCount);
            if (localActiveCount == 0 && this.IsAddingCompleted)
        }, TaskContinuationOptions.ExecuteSynchronously);

    public void CompleteAdding()
        Interlocked.Exchange(ref _isAddingCompleted, 1);
        if (this.ActiveCount == 0) _tcs.TrySetResult(true);
public static TaskAggregator LogTasksAggregator = new TaskAggregator();

public static void Log(string str)
    var logTask = Console.Out.WriteLineAsync(str);

// End of program
bool completedInTime = LogTasksAggregator.Task.Wait(5000);
if (!completedInTime)
    Console.WriteLine("LogTasksAggregator timed out");

Share : facebook icon twitter icon
Threading.Tasks: Concept of WaitAll()

Threading.Tasks: Concept of WaitAll()

Date : March 29 2020, 07:55 AM
it fixes the issue Just for the sake of argument I did a little test (shown below) - it demonstrates one of your tasks is hanging, and not returning a value.
code :
        Task<int> task1 = Task<int>.Factory.StartNew(() =>
            return 10;
        Task<int> task2 = Task<int>.Factory.StartNew(() => 15);
        Task<int>[] tasks = {task1, task2};
            Stopwatch sw = new Stopwatch();
            Console.WriteLine(String.Format("tasks completed in {0}ms", sw.ElapsedMilliseconds));
Recursion with Tasks and WaitAll

Recursion with Tasks and WaitAll

By : Amruta
Date : March 29 2020, 07:55 AM
hope this fix your issue Make GetAllCandidates keep a function-local list of tasks started. At the end of the function wait for them. This still provides parallelism as long as you start more than 1 task.
How to use the CancellationToken with Tasks.WaitAll()

How to use the CancellationToken with Tasks.WaitAll()

By : user3092180
Date : March 29 2020, 07:55 AM
hop of those help?
Since Task.WaitAll is a blocking operation, how could you possibly "observe" it during that operation?
How to get return value of tasks when using Task.WaitAll()

How to get return value of tasks when using Task.WaitAll()

By : Alfonso
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I need to get the return value of multiple Task> executed in parallel and merge them into a new List. , You could try to use the SelectMany method:
code :
var result = TaskList.Select(t => t.Result)
                     .SelectMany(r => r)
var TaskList = new List<Task<List<string>>();
Child Tasks Vs WaitAll

Child Tasks Vs WaitAll

By : Dũng Trần
Date : March 29 2020, 07:55 AM
seems to work fine AttachedToParent offers you a different way to structure your code. If child Tasks can start in various places in the code of the parent Task, using AttachedToParent means you don't have to worry about collecting all the child Tasks into a collection.
In practice, I think that Task.WaitAll() is clearer and collecting the Task is not actually a problem, so I would almost never use AttachedToParent.
Related Posts Related Posts :
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • How to convert API Json response to C# Array?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org