Skip to content

Instantly share code, notes, and snippets.

@danielmarbach
Created September 28, 2017 20:40
Show Gist options
  • Save danielmarbach/8b924cb212b6d843b1cf0b5b5d92dd7c to your computer and use it in GitHub Desktop.
Save danielmarbach/8b924cb212b6d843b1cf0b5b5d92dd7c to your computer and use it in GitHub Desktop.
Ardalis Blog
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