Skip to content

Instantly share code, notes, and snippets.

@lsmithmier
Created June 30, 2016 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsmithmier/f9f3b5e4c75840bd0dd448843597f68d to your computer and use it in GitHub Desktop.
Save lsmithmier/f9f3b5e4c75840bd0dd448843597f68d to your computer and use it in GitHub Desktop.
Example of handling exceptions in a task list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestListAsyncAndExceptions
{
class Program
{
static void Main(string[] args)
{
using (System.CodeDom.Compiler.IndentedTextWriter writer = new System.CodeDom.Compiler.IndentedTextWriter(Console.Out, " "))
{
Console.SetOut(writer);
var taskList = new List<Task> {
GoodTask(100,"A"),
GoodTask(300,"B"),
GoodTask(200,"C"),
BadTask(500,"D"),
GoodTask(400,"E"),
BadTask(600,"F",new Exception("Generic Exception")),
GoodTask(900,"G"),
BadTask(800,"H",new DivideByZeroException("Woot, 1/0 blew it up")),
GoodTask(700,"I"),
};
Console.WriteLine("Start Waiting");
try
{
Task.WaitAll(taskList.ToArray());
}
catch (Exception myException)
{
Console.WriteLine(myException.Message);
foreach (var innerException in taskList.Where(x=>x.IsFaulted))
{
writer.Indent = 1;
Console.WriteLine(innerException.Exception.InnerException.Message);
writer.Indent = 0;
}
}
Console.WriteLine("Done Waiting");
}
Console.ReadLine();
}
public static async Task GoodTask(int delayTime, string name)
{
await Task.Delay(delayTime);
Console.WriteLine(name);
}
public static async Task BadTask(int delayTime, string name)
{
await BadTask(delayTime, name, new Exception("You left the exceptionToThrow argument of BadTask empty"));
}
public static async Task BadTask(int delayTime, string name, Exception exceptionToThrow)
{
await Task.Delay(delayTime);
Console.WriteLine(name);
throw exceptionToThrow;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment