Skip to content

Instantly share code, notes, and snippets.

@iamsunny
Last active March 12, 2018 08:31
Show Gist options
  • Save iamsunny/53091337d461dc5511e083696d32fa25 to your computer and use it in GitHub Desktop.
Save iamsunny/53091337d461dc5511e083696d32fa25 to your computer and use it in GitHub Desktop.
Methods to Test Async/Await execution
static void Main(string[] args)
{
//initialize an stopwatch
var sw = new Stopwatch();
// run "TestAsyncMethods"
sw.Start();
Execute().GetAwaiter().GetResult();
sw.Stop();
Console.WriteLine($"Done! Completed in {sw.Elapsed}");
Console.WriteLine();
// run "TestAsyncMethodsWithConfigureAwait"
sw.Restart();
ExecuteWithConfigureAwait().GetAwaiter().GetResult();
sw.Stop();
Console.WriteLine($"Done! Completed in {sw.Elapsed}");
Console.WriteLine();
// run "TestAsyncMethodsWithTaskRun"
sw.Restart();
ExecuteWithTaskRun().GetAwaiter().GetResult();
sw.Stop();
Console.WriteLine($"Done! Completed in {sw.Elapsed}");
Console.WriteLine();
// wait for a key press
Console.ReadKey();
}
// Execute() - awaits each task individually
static async Task<bool> Execute()
{
var asyncMethods = new AsyncMethods();
// run tasks
//run task 1 for 1 second
await asyncMethods.SleepAsync(1);
//run task 2 for 2 second
await asyncMethods.SleepAsync(2);
//run task 3 for 3 second
await asyncMethods.SleepAsync(3);
return false;
}
// ExecuteWithConfigureAwait() - awaits each task individually with .ConfigureAwait(false)
static async Task<bool> ExecuteWithConfigureAwait()
{
var asyncMethods = new AsyncMethods();
// run tasks with.ConfigureAwait(false)
//run task 1 for 1 second
await asyncMethods.SleepAsync(1).ConfigureAwait(false);
//run task 2 for 2 second
await asyncMethods.SleepAsync(2).ConfigureAwait(false);
//run task 3 for 3 second
await asyncMethods.SleepAsync(3).ConfigureAwait(false);
return false;
}
// ExecuteWithTaskRun() - awaits all tasks at once
static async Task<bool> ExecuteWithTaskRun()
{
var asyncMethods = new AsyncMethods();
var tl = new List<Task>
{
//run task 1 for 1 second
Task.Run(() => asyncMethods.SleepAsync(1)),
//run task 2 for 2 seconds
Task.Run(() => asyncMethods.SleepAsync(2)),
//run task 3 for 3 seconds
Task.Run(() => asyncMethods.SleepAsync(3))
};
Task.WaitAll(tl.ToArray());
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment