Skip to content

Instantly share code, notes, and snippets.

@Benjin
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Benjin/b55dcd90bd7a47f307d5 to your computer and use it in GitHub Desktop.
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.
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