Created
October 21, 2018 12:09
-
-
Save mariusGundersen/aaa0af25c481531e5a0fc4a3e7db1233 to your computer and use it in GitHub Desktop.
Duct-type extension methods Example 5
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.Runtime.CompilerServices; | |
using System.Threading.Tasks; | |
// Example 5: await tuple of Tasks | |
// Just some dummy async functions | |
public static Task<string> GetSomethingAsync(int number) => Task.FromResult($"Something {number}"); | |
public static Task<int> GetAnotherThingAsync(string text) => Task.FromResult(text.Length); | |
// This extension method lets us await a tuple with two values | |
public static TaskAwaiter<(T1, T2)> GetAwaiter<T1, T2>(this (Task<T1>, Task<T2>) tasks) | |
=> Task.WhenAll(tasks.Item1, tasks.Item2).ContinueWith(_ => (tasks.Item1.Result, tasks.Item2.Result)).GetAwaiter(); | |
// Now we can await the tuple directly | |
var (something, anotherThing) = await (GetSomethingAsync(10), GetAnotherThingAsync("something")); | |
// There is a bug in try.dot.net that causes the above line to fail, but it works in Visual Studio. | |
// You can try this line instead just to see how it works, it's exactly the same just without the syntax sugar | |
// var (something, anotherThing) = await System.ValueTuple.Create(GetSomethingAsync(10), GetAnotherThingAsync("something")); | |
Console.WriteLine(something); | |
Console.WriteLine(anotherThing); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment