Skip to content

Instantly share code, notes, and snippets.

@liorksh

liorksh/Task Wait.cs Secret

Created Apr 26, 2020
Embed
What would you like to do?
Example of Task.WaitAll and Task.WaitAny
[Theory]
[InlineData(456, 10)]
public async void TaskWaitOptions(int initialNumberOfBooks, int numberOfTasks)
{
Random rnd = new Random();
List<Task> lstTasks = new List<Task>();
LibraryAccount acc = new LibraryAccount(initialNumberOfBooks);
for (int i = 0; i < numberOfTasks; i++)
{
Task t = new Task(() =>
{
acc.WithdrawBooksWithExecuterName(rnd.Next(1, 12), "Thread_" + DateTime.Now.Ticks);
});
lstTasks.Add(t);
// Starting the task in various times
Task.Delay(rnd.Next(3000, 10000)).ContinueWith((p)=> { t.Start(); });
}
await Task.Delay(5000);
int index = Task.WaitAny(lstTasks.ToArray());
Trace.WriteLine($">>> The task in index {index} is completed; waiting for the rest to complete");
Task.WaitAll(lstTasks.ToArray());
Trace.WriteLine($">>> All the tasks were completed");
}
/* The output:
26/04/2020 03:28:33: Inside thread Thread_637235117129167455, trying to withdraw 1 while the current balance is 456
26/04/2020 03:28:33: Inside thread Thread_637235117129229866, trying to withdraw 8 while the current balance is 455
26/04/2020 03:28:34: Inside thread Thread_637235117143485059, trying to withdraw 7 while the current balance is 447
>>> The task in index 1 is completed; waiting for the rest to complete
26/04/2020 03:28:34: Inside thread Thread_637235117147239496, trying to withdraw 6 while the current balance is 440
26/04/2020 03:28:35: Inside thread Thread_637235117158681339, trying to withdraw 6 while the current balance is 434
26/04/2020 03:28:36: Inside thread Thread_637235117168349816, trying to withdraw 9 while the current balance is 428
26/04/2020 03:28:37: Inside thread Thread_637235117169743204, trying to withdraw 4 while the current balance is 419
26/04/2020 03:28:38: Inside thread Thread_637235117183844764, trying to withdraw 3 while the current balance is 415
26/04/2020 03:28:38: Inside thread Thread_637235117185905806, trying to withdraw 5 while the current balance is 412
26/04/2020 03:28:39: Inside thread Thread_637235117192056999, trying to withdraw 6 while the current balance is 407
>>> All the tasks were completed
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.