Last active
August 29, 2015 14:11
-
-
Save Benjin/b55dcd90bd7a47f307d5 to your computer and use it in GitHub Desktop.
Demonstrates proper use of async and await keywords, and breaking back into synchronous code without any duplication of logic.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Diagnostics; | |
using ExtensionMethods; | |
namespace TaskTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
MainAsync().Wait(); | |
Console.WriteLine("\nPress any key to end."); | |
Console.ReadKey(); | |
} | |
static async Task MainAsync() | |
{ | |
Stopwatch s = Stopwatch.StartNew(); | |
s.Checkpoint("Very beginning"); | |
s.Checkpoint("Before sync start"); | |
Foo f1 = MakeAFoo(); | |
s.Checkpoint("After sync end"); | |
Console.WriteLine("\n\n"); | |
s.Checkpoint("Before async start"); | |
Task<Foo> f2Task = MakeAFooAsync(); | |
s.Checkpoint("After async return"); | |
// we can continue doing whatever we want here, as long as it doesn't rely on the result from f2Task | |
Foo f2 = await f2Task; | |
s.Checkpoint("After awaited Task"); | |
} | |
public static async Task<Foo> MakeAFooAsync() | |
{ | |
await Task.Delay(3000); // could be anything - constructing an object, calling a server... | |
return new Foo(); | |
} | |
public static Foo MakeAFoo() | |
{ | |
return MakeAFooAsync().Result; | |
} | |
} | |
class Foo { } | |
} | |
namespace ExtensionMethods | |
{ | |
public static class ExtensionMethods | |
{ | |
public static void Checkpoint(this Stopwatch sw, string note = "", int indentSize = 0) | |
{ | |
Console.WriteLine("{0}Checkpoint: {1} ms; {2}", String.Concat(Enumerable.Repeat("\t", indentSize)), sw.ElapsedMilliseconds, note); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment