Consider a situation where I have three (or more) ways of performing a calculation, each of which can fail with an exception. In order to attempt each calculation until we f
You can use a Task/ContinueWith, and check for the exception. Here's a nice extension method to help make it pretty:
static void Main() {
var task = Task.Factory.StartNew(Calc1)
.OrIfException(Calc2)
.OrIfException(Calc3)
.OrIfException(Calc4);
Console.WriteLine(task.Result); // shows "3" (the first one that passed)
}
static double Calc1() {
throw new InvalidOperationException();
}
static double Calc2() {
throw new InvalidOperationException();
}
static double Calc3() {
return 3;
}
static double Calc4() {
return 4;
}
}
static class A {
public static Task OrIfException(this Task task, Func nextOption) {
return task.ContinueWith(t => t.Exception == null ? t.Result : nextOption(), TaskContinuationOptions.ExecuteSynchronously);
}
}