Skip to content

Instantly share code, notes, and snippets.

@ScriptBytes
Created March 30, 2022 03:31
Show Gist options
  • Save ScriptBytes/dbfa7827ed9e5f93a9ec06d31e7d7de8 to your computer and use it in GitHub Desktop.
Save ScriptBytes/dbfa7827ed9e5f93a9ec06d31e7d7de8 to your computer and use it in GitHub Desktop.
Quick and ugly example of the benefits of using Task.WhenAll for running many concurrent Tasks
using System.Diagnostics;
var numTasks = 10;
var taskTimeMs = 1000;
Console.WriteLine($"Running {numTasks} tasks at {taskTimeMs} ms each.");
Stopwatch stopWatch = new Stopwatch();
await DoSlow();
await DoFast();
async Task DoFast()
{
Console.WriteLine("Using Task.WhenAll");
List<Task> tasks = new List<Task>();
for (int i = 0; i < numTasks; i++)
{
tasks.Add(Task.Run(() => Thread.Sleep(taskTimeMs)));
}
StartStopwatch();
await Task.WhenAll(tasks);
StopStopwatch();
PrintElapsedTime();
}
async Task DoSlow()
{
Console.WriteLine("Using sequential tasks");
StartStopwatch();
for (int i = 0; i < numTasks; i++)
{
await Task.Run(() => Thread.Sleep(taskTimeMs));
}
StopStopwatch();
PrintElapsedTime();
}
void StartStopwatch()
{
stopWatch.Restart();
}
void StopStopwatch()
{
stopWatch.Stop();
}
void PrintElapsedTime()
{
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment