Created
August 24, 2019 21:50
-
-
Save kekyo/7b54519d44e5238b8ada98a53419ede9 to your computer and use it in GitHub Desktop.
Continuation vs Awaiting.
This file contains hidden or 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.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