Snippets tagged async

An asynchronous sequence is similar to the seq type, but the elements of the sequence are generated asynchronously without blocking the caller as in Async. This snippet declares asynchronous sequence and uses it to compare two files in 1k blocks.

A functional wrapper around the new WCF Web APIs (http://wcf.codeplex.com/). Composition is achieved through the use of the HttpRequestMessage -> Async signature.
Pushing the app calls in the MessageHandler intercepts all requests and allows you to take control at the earliest point possible before operation selection occurs. Extending this slightly to call the innerChannel's SendAsync would allow you to create a middleware layer that would work both with this and other, normal Web API services.

An asynchronous SNTP client that can retrieve the current time from an internet time server (such as time-a.nist.gov) and optionally update the local system clock to match. Demonstrates async UDP communication, bit-shifting, and native interop/PInvoke.

Similar to an async { } block but captures the result for future consumption. This structure can be very useful for performing multiple result-returning operations in parallel when the results aren't needed immediately. For example, performing several read/transform operations or pre-populating a cache with yet-to-be computed values. Microsoft's Task Parallel Library in .NET 4.0 includes a Future implementation so this version is only needed on earlier .NET versions. Comments, suggestions, and improvements are always welcome.

This snippet shows two improvements to asynchronous HTTP proxy from: http://fssnip.net/6e. First extension is to process page in chunks (instead of downloading the entire content first). The second extension is to use simple agent-based in-memory cache for previously visited pages.

Async is a very versatile structure, which has been used to compose CPU/IO bound computations.
So it is very tempting to implement a MapReduce function based on Async and borrowing ideas from the theory of list homomorphisms.

This snippet demonstrates programming using asynchronous sequences. It contains (hidden) implementation of AsyncSeq type and combinators for working with it. More importantly, it demonstrates how to use asynchronous sequences to implement a simple sequential on-demand crawler.

The snippet uses asynchronous sequences (from F# AsyncExtensions) to download historical stock data from Yahoo. Data is downloaded in a buffered way on demand (as needed) and returned line by line. The sample then prints OHLC values for first 30 items.

Non-deterministic choice operation for F# asynchronous workflows - creates a workflow that returns the result of one of two asynchronous workflows, depending on which completes first. (The other workflow is not cancelled.)

The snippet shows a simple F# agent that calculates average from the received values. It supports one message for adding numbers to the statistics and one for resetting the state. Moreover, the agent limits the processing rate to 1 message per second.

TicTacToe game simulator implemented by using Joinads(http://tomasp.net/blog/joinads-async-prog.aspx).
Game logic in this snippet was simplified so nicely by using Joinads.
You can run this snippet on Try Joinads (http://tryjoinads.org/).

A set of Async primitives as described by Dave Thomas [1] (and derived from Stephen Toub [2]).
[1] http://moiraesoftware.com/blog/2012/04/22/back-to-the-primitive-ii/
[2] http://blogs.msdn.com/b/pfxteam/archive/2012/02/11/10266923.aspx

An extension of MailboxProcessor that catches all unhandled exceptions (in the body of the mailbox processor) and reports them using an event. Otherwise, the public interface is the same as for MailboxProcessor.

This is an implementation of the Async.Choice combinator that composes a sequence of workflows into one whose result is that of the first workflow that returns a *valid* result. You can think of it as a nondeterministic version of (Seq.tryPick id). This implementation draws ideas from Tomas Petricek's choice implementation in http://fssnip.net/6D.
UPDATE (11/2015):
Following the discussion in https://fslang.uservoice.com/forums/245727-f-language/suggestions/10575069-add-async-choice-to-fsharp-core I have updated the snippet.

A simple implementation that protects the nested workflow from external cancellation. The external cancellation token is passed as an argument for cooperative cancellation. Kudos to Gian Ntzik for this one.

A simple asynchronous workflow that retries running a given async workflow (until "resultOk" function returns true or until a specified number of retries is performed). The function uses tail-recursion in async workflows.

Perform parallel Async returning heterogeneous types.
(The solution presented here is based on a gist sent to me by [Anton Tayanovskyy](http://t0yv0.blogspot.com/ "Anton Tayanovskyy"), Twitter: [@t0yv0](https://twitter.com/t0yv0).)

Joinads example from here https://github.com/tpetricek/FSharp.Joinads/blob/master/README.markdown translated to Hopac. No language extension needed, the code is equally compact and arguably more readable.

F# computation expressions do not allow monadic expressions inside `finally` clauses. If we allow ourselves a bit of ugliness this can be circumvented by using a combinator. Here's an implementation for asynchronous workflows and a small application.

There are several maze creation algorithms (http://www.astrolog.org/labyrnth/algrithm.htm). The interesting point about Growing Tree one is that it turns into the others (for example, Recursive Backtracker and Prim's algo) when we choose the next step in different ways. Check it with tryfsharp.org.

The snippet declares a helper for creating asynchronous controllers for ASP.NET MVC 3. It declares a new base class for asynchronous actions that exposes a computation builder for writing actions using F# asynchronous workflows.

The snippet overrides default AsyncControllerActionInvoker so F# async workflows can be used for ASP.NET MVC 3. It declares a new base class for asynchronous controller. Controller method has to have return type Async.

This is a simple implementation of an object pool using an agent (MailboxProcessor).
The pool is created with an initial number of object using the specified generator.
The ObjectPool has three functions:
Put: An item can be 'Put' into the pool.
Get: An item can be taken from the pool
ToListAndClear: A list of all the items in the pool is returned and the pool is cleared.

An agent based scheduler, can be sent a single schedule message (ScheduleOnce) and multiple schedule message (Schedule).
The schedule messages comprise of a function to receive the message, the message, an initial TimeSpan before the message is scheduled, and another timespan for the schedule repeat.
Check out my blog below for more details:
http://bit.ly/mK4prb

This snippet shows the implementation of three HTTP proxy servers in F#. The first is written using simple synchronous style (that isn't scalable). The second version uses event-based approach in the Node.js style, but is difficult to write. The third version uses F# async workflows and is both scalable and easy to write.

The snippet implements Async.Choice method that takes several workflows and creates a workflow, which returns the first result that was computed. After a workflow completes, remaining workflows are cancelled using the F# async cancellation mechanism. (The method doesn't handle exceptions.)

Generic batch job processor using Mail box processor. Sending quit message using PostAndReply will ensure that all jobs are completed before returning. (Exception handling is responsibility of the job)

Implements a simple Async.StartDisposable extension that can be used to easily create IObservable values from F# asynchronous workflows. The method starts an asynchronous workflow and returns IDisposable that cancels the workflow when disposed.

Implementation of Async.Sleep in f# 2.0 doesn't allow break it execution until the time elapsed. Here is the alternate implementation which support immediate cancellation. According to discussion http://stackoverflow.com/questions/9041491/is-there-any-reason-why-async-sleep-can-not-be-canceled-immediately .

Given a NuGet package name, this code will download the package, extract it to a temp directory, and return a sequence of FileInfo objects representing assemblies from that package, with a preference for .NET 4.5 and 4.0 assemblies, if present. Requires the "DotNetZip" package.

The snippet implements Async.StartCancellable method that can be used to start a given workflow and then cancel it. The cancellation of the workflow is done asynchronously, which means that the caller will wait until the workflow is actually cancelled.

AsyncBuilder extension for maniplating some other containers directory in asynchronous workflow.
Bind methods in the extension enables you to retrieve inner values of 'a IObservable and 'a IEvent by using let! or do! keyword without Async.AwaitEvent or AsyncAwaitObservable.
For method in the extension omits let! binding.
Yield method in the extension enables you to yield value in for expression in asynchronous workflow.

If you have read the awesome book by Jeffrey Richter CLR via C# 4 ed. you have discovered that there are more optimal ways for thread synchronization than the one provided by the BCL. One of them is the use of new asynchronous capabilities in order to create an asynchronous synchronization primitive. In the book it is presented an AsyncOneManyLock which is used for thread synchornization for code with a high demand for responsiveness and scalability.
If you are an F# developer you know that the F# Asynchornous Workflow and the Task Parallel Library are different, so I decided to port this useful piece of code to F# and show you how to use it with an example.

A simple computational expression to deal with asynchronous calls that return a choice type to signal failure.
Useful for calling remote services that may fail - you can call the remote service with functions of type "request -> Async>" and then chain the results together.

The snippet implements a simple agent that limits the number of parallelism. When created, the agent takes the maximum number of tasks it can run in parallel. When it receives a "Start" message, it will then either run the task, or store it in a queue until earlier task ha completed.

One of the main features of Hopac - selective synchronization using "alternatives". In this snippet we download three web pages in parallel and the one that finishes first "wins" (or the timeout alternative becomes available for picking). What's nice in this solution is that the other two downloading jobs are cancelled immediately when the winner/timeout is available (i.e. an implicitly provided to the Asyncs CancellationTokens are cancelled).
Alts is highly composable and, for example, the whole Alt.choose [ ... ] thing could be nested in another Alt.choose or combined with or operators with another Alt and so on.

An extension of MailboxProcessor that catches all unhandled exceptions, and ensures that the user-provided function is run repeatedly until it returns normally. Based on the HandlingMailbox defined by Tomas Petricek: fssnip.net/cj

This is a simple code implementation to copy Streams leveraging the Async workflow.
After the first read, the write and read processes are done in parallel. I also used an Array of Array as buffer to avoid false sharing memory. An other improvment option could be to increase the buffer size if the copy is done in same machine.