Created
September 7, 2016 02:44
-
-
Save waf/c9285d4e75da17733dffee46eb449933 to your computer and use it in GitHub Desktop.
async/await behavior without the keywords
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; | |
namespace Scratch | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var sum = from a in Task.Run(() => 3) // 3 | |
from b in AddAsync(a, 2) // 5 | |
from result in AddAsync(a, b) // 8 | |
select a + b + result; // 16 | |
Console.WriteLine(sum.Result); | |
Console.ReadKey(); | |
} | |
/// <summary> | |
/// A sample async method for testing | |
/// </summary> | |
public static Task<int> AddAsync(int x, int y) | |
{ | |
return Task.Run(() => x + y); | |
} | |
} | |
public static class AsyncExtensions | |
{ | |
public static Task<TResult> SelectMany<TSource, TSelector, TResult> | |
(this Task<TSource> source, | |
Func<TSource, Task<TSelector>> selector, | |
Func<TSource, TSelector, TResult> resultSelector) | |
{ | |
return source | |
.ContinueWith(result => selector(result.Result) | |
.ContinueWith(result2 => resultSelector(result.Result, result2.Result))) | |
.Unwrap(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment