Created
September 28, 2017 20:40
-
-
Save danielmarbach/8b924cb212b6d843b1cf0b5b5d92dd7c to your computer and use it in GitHub Desktop.
Ardalis Blog
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.Diagnostics; | |
using System.Threading.Tasks; | |
namespace AsyncSandbox | |
{ | |
class Program | |
{ | |
static async Task Main(string[] args) | |
{ | |
var partyStatus = new PartyStatus(); | |
var timer = Stopwatch.StartNew(); | |
var sendInvites = SendInvites(); | |
var orderFood = OrderFood(); | |
var cleanHouse = CleanHouse(); | |
var useResult = true; // set this to true|false | |
try | |
{ | |
await Task.WhenAll(sendInvites, orderFood, cleanHouse) | |
.ContinueWith(async t => | |
{ | |
t.Exception.Handle(e => true); | |
if (useResult) | |
{ | |
partyStatus.InvitesSent = sendInvites.Result; | |
partyStatus.FoodCost = orderFood.Result; | |
partyStatus.IsHouseClean = cleanHouse.Result; | |
} | |
else | |
{ | |
partyStatus.InvitesSent = await sendInvites; | |
partyStatus.FoodCost = await orderFood; | |
partyStatus.IsHouseClean = await cleanHouse; | |
} | |
}).Unwrap(); | |
} | |
catch (AggregateException) | |
{ | |
Console.WriteLine("AggregateException"); | |
} | |
catch (InvalidOperationException) | |
{ | |
Console.WriteLine("InvalidOperationException"); | |
} | |
Console.WriteLine($"Elapsed time: {timer.ElapsedMilliseconds}ms"); | |
Console.ReadLine(); | |
} | |
public static async Task<int> SendInvites() | |
{ | |
await Task.Delay(2000); | |
throw new InvalidOperationException(); | |
return 100; | |
} | |
public static async Task<decimal> OrderFood() | |
{ | |
await Task.Delay(2000); | |
return 123.23m; | |
} | |
public static async Task<bool> CleanHouse() | |
{ | |
await Task.Delay(2000); | |
return true; | |
} | |
class PartyStatus | |
{ | |
public int InvitesSent { get; set; } | |
public decimal FoodCost { get; set; } | |
public bool IsHouseClean { get; set; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment