Skip to content

Instantly share code, notes, and snippets.

@aliabidzaidi
Created June 1, 2019 10:16
Show Gist options
  • Save aliabidzaidi/2fc6287be60e069dd5e2c7c4bc34c000 to your computer and use it in GitHub Desktop.
Save aliabidzaidi/2fc6287be60e069dd5e2c7c4bc34c000 to your computer and use it in GitHub Desktop.
Different ways to wait for tasks
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
Task T1 = new Task(() => { Console.WriteLine("Task 1"); }, token);
Task T2 = new Task(() => { Console.WriteLine("Task 2"); }, token);
T1.Start();
T2.Start();
//Number of ways to achieve wait
T1.Wait(); //Simple wait for task to complete execution
T1.Wait(2000); //Wait for Number of milliseconds
T1.Wait(token); //Wait for Task to complete execution or terminates if task is cancelled
T1.Wait(2000, token); //Wait for milliseconds or terminates if task is cancelled
Task.WaitAll(T1, T2); // Wait For All Tasks
int completedTaskIndex = Task.WaitAny(T1, T2); //Waits for One or Many Tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment