Created
March 31, 2014 19:10
-
-
Save Rohansi/9899838 to your computer and use it in GitHub Desktop.
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.Linq; | |
using System.Threading.Tasks; | |
using System.Threading.Tasks.Dataflow; | |
using System.Numerics; | |
namespace dataflow | |
{ | |
class Message | |
{ | |
public readonly TaskCompletionSource<BigInteger> Completion; | |
public Task<BigInteger> Result { get { return Completion.Task; } } | |
public readonly BigInteger N; | |
public Message(BigInteger n) | |
{ | |
Completion = new TaskCompletionSource<BigInteger>(); | |
N = n; | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
var factorialServer = new ActionBlock<Message>( | |
msg => msg.Completion.SetResult(Factorial(msg.N)), | |
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 }); | |
var fibonacciServer = new ActionBlock<Message>( | |
msg => msg.Completion.SetResult(Fibonacci(msg.N)), | |
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 }); | |
Parallel.ForEach(Enumerable.Range(0, 1000), async i => | |
{ | |
var factMsg = new Message(i); | |
factorialServer.Post(factMsg); | |
var fibMsg = new Message(i); | |
fibonacciServer.Post(fibMsg); | |
Console.WriteLine("{0} -> {1}", i, Tuple.Create(await factMsg.Result, await fibMsg.Result)); | |
}); | |
factorialServer.Complete(); | |
factorialServer.Completion.Wait(); | |
} | |
static BigInteger Factorial(BigInteger n) | |
{ | |
if (n == 0) | |
return 1; | |
BigInteger value = 1; | |
for (BigInteger i = n; i > 0; i--) | |
{ | |
value *= i; | |
} | |
return value; | |
} | |
static BigInteger Fibonacci(BigInteger n) | |
{ | |
BigInteger a = 0; | |
BigInteger b = 1; | |
for (BigInteger i = 0; i < n; i++) | |
{ | |
BigInteger temp = a; | |
a = b; | |
b = temp + b; | |
} | |
return a; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment