Skip to content

Instantly share code, notes, and snippets.

@Bomret
Last active December 23, 2015 19:38
Show Gist options
  • Save Bomret/6683571 to your computer and use it in GitHub Desktop.
Save Bomret/6683571 to your computer and use it in GitHub Desktop.
The simplest Future constructs available in C#. The first one is an Action that takes a Func that produces a value (the work) and an Action that consumes the result (the callback) as parameters. The second is a Func that takes a Func that produces a value as parameter (the work to do) and returns an Action that calls another Action, provided by …
class Program
{
static void Main(string[] args)
{
// first implementation with callback provided directly
Action<Func<int>, Action<int>> future =
(work, callback) => ThreadPool.QueueUserWorkItem(_ => callback(work()));
// example application (will print "Result: 3")
future(() => 1 + 2, result => Console.WriteLine("Result: {0}", result));
// second implementation with callback provided via currying
Func<Func<int>, Action<Action<int>>> curriedFuture =
work => callback => ThreadPool.QueueUserWorkItem(_ => callback(work()));
// example application (will print "Result: 5")
curriedFuture(() => 2 + 3)(result => Console.WriteLine("Result: {0}", result));
// keep the app from closing before the callbacks have been called
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment