Skip to content

Instantly share code, notes, and snippets.

@kekyo
Created August 24, 2019 21:50
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 kekyo/7b54519d44e5238b8ada98a53419ede9 to your computer and use it in GitHub Desktop.
Save kekyo/7b54519d44e5238b8ada98a53419ede9 to your computer and use it in GitHub Desktop.
Continuation vs Awaiting.
using System;
using System.Threading.Tasks;
namespace ConsoleApp5
{
public static class Program
{
private static async Task ContinuationWithAwaitingSimple()
{
Console.WriteLine("Before");
await Task.Delay(5000);
Console.WriteLine("After");
}
private static Task ContinuationWithDelegateSimple()
{
Console.WriteLine("Before");
return Task.Delay(5000).ContinueWith(task =>
{
Console.WriteLine("After");
});
}
private static async Task ContinuationWithAwaitingComplex()
{
Console.WriteLine("Before");
for (var index = 0; index < 10; index++)
{
await Task.Delay(1000);
Console.WriteLine("Interval: " + index);
}
Console.WriteLine("After");
}
private static Task ContinuationWithDelegateComplex()
{
Console.WriteLine("Before");
var tcs = new TaskCompletionSource<object>();
var index = 0;
void continuation(Task task)
{
Console.WriteLine("Interval: " + index);
index++;
if (index < 10)
{
Task.Delay(1000).ContinueWith(continuation);
}
else
{
Console.WriteLine("After");
tcs.SetResult(null);
}
};
Task.Delay(1000).ContinueWith(continuation);
return tcs.Task;
}
static async Task Main(string[] args)
{
await ContinuationWithDelegateSimple();
await ContinuationWithAwaitingSimple();
await ContinuationWithDelegateComplex();
await ContinuationWithAwaitingComplex();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment