Created
June 21, 2016 14:02
-
-
Save eouw0o83hf/32b5fd287147e791c1bcae972892e9b6 to your computer and use it in GitHub Desktop.
Tasks in Serial and Parallel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Converting serially took 3126 ms | |
Converting parallelly took 323 ms |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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