Skip to content

Instantly share code, notes, and snippets.

@joshka
Created August 2, 2014 05:17
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 joshka/7724c8d23725d0addaed to your computer and use it in GitHub Desktop.
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.
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));
}
}
}
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