Skip to content

Instantly share code, notes, and snippets.

@eouw0o83hf
Created June 21, 2016 14:02
Show Gist options
  • Save eouw0o83hf/32b5fd287147e791c1bcae972892e9b6 to your computer and use it in GitHub Desktop.
Save eouw0o83hf/32b5fd287147e791c1bcae972892e9b6 to your computer and use it in GitHub Desktop.
Tasks in Serial and Parallel
Converting serially took 3126 ms
Converting parallelly took 323 ms
async void Main()
{
var serialData = await ConvertSerially();
var parallelData = await ConvertParallelly();
}
async Task<ICollection<string>> ConvertSerially()
{
var convertedList = new List<string>();
var stopwatch = Stopwatch.StartNew();
foreach(var i in SeedData())
{
var value = await ConvertToStringExpensively(i);
convertedList.Add(value);
}
stopwatch.Stop();
Console.WriteLine("Converting serially took {0} ms", stopwatch.ElapsedMilliseconds);
return convertedList;
}
async Task<ICollection<string>> ConvertParallelly()
{
var stopwatch = Stopwatch.StartNew();
var tasks = SeedData()
.Select(async a => await ConvertToStringExpensively(a));
var convertedList = await Task.WhenAll(tasks);
stopwatch.Stop();
Console.WriteLine("Converting parallelly took {0} ms", stopwatch.ElapsedMilliseconds);
return convertedList;
}
IEnumerable<int> SeedData()
{
return Enumerable.Range(300, 10);
}
async Task<string> ConvertToStringExpensively(int input)
{
await Task.Delay(input);
return input.ToString();
}
// Define other methods and classes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment