Created
August 2, 2014 05:17
-
-
Save joshka/7724c8d23725d0addaed to your computer and use it in GitHub Desktop.
Calculate Fibonacci by using parallel tasks and aggregate exceptions. I did it for the cookie.
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.Threading.Tasks; | |
namespace Fib | |
{ | |
class ExceptionalFibonacciCalculator | |
{ | |
public int Calculate(uint n) | |
{ | |
try | |
{ | |
Fibonacci(n).Wait(); | |
} | |
catch (AggregateException e) | |
{ | |
return e.Flatten().InnerExceptions.Count; | |
} | |
throw new InvalidOperationException("Should never hit this"); | |
} | |
static Task Fibonacci(uint n) | |
{ | |
return n <= 1 | |
? Task.Factory.StartNew( | |
() => { throw new Exception(); }, | |
TaskCreationOptions.AttachedToParent) | |
: Task.WhenAll( | |
Task.Factory.StartNew( | |
() => Fibonacci(n - 1), | |
TaskCreationOptions.AttachedToParent), | |
Task.Factory.StartNew( | |
() => Fibonacci(n - 2), | |
TaskCreationOptions.AttachedToParent)); | |
} | |
} | |
} |
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; | |
namespace Fib | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
var fib = new ExceptionalFibonacciCalculator(); | |
for (uint n = 0; n < 25; n++) | |
{ | |
var result = fib.Calculate(n); | |
Console.WriteLine("Fibonacci({0})={1}", n, result); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment