I have not not given this enough scrunity to ensure it's correct, but here's a general async throttle you might find useful (along with sample use):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
let throttleParallelAtMost<'r> maxActive work = 
    let mre = new System.Threading.AutoResetEvent(false)
    let numActive = ref 0
    let throttle = MailboxProcessor<_>.Start(fun inbox ->
        async {
            let nextWork (f, replyChannel:AsyncReplyChannel<'r>) = async {
                let! r = f
                replyChannel.Reply(r)
                System.Threading.Interlocked.Decrement(&numActive.contents) |> ignore
                mre.Set() |> ignore }
            while true do
                let! msg = inbox.Receive()
                let next = System.Threading.Interlocked.Increment(&numActive.contents)
                if next <= maxActive then
                    Async.Start(nextWork msg)
                else
                    let! _ = Async.AwaitWaitHandle mre
                    Async.Start(nextWork msg)
        } )
    work
    |> Array.map (fun guy -> throttle.PostAndAsyncReply(fun rc -> guy, rc))
    |> Async.Parallel 
 
let sleep (n:int) = async {
    System.Console.WriteLine("Guy #{0} about to sleep", n)
    do! Async.Sleep(1000)
    System.Console.WriteLine("Guy #{0} woke up", n)
    return n
    }
 
let work =
    Array.init 25 sleep
 
printfn "about to run 5-throttled"
 
let results = 
    work
    |> throttleParallelAtMost 5
    |> Async.RunSynchronously 
 
printfn "done: %A" results
 
 
By on 1/12/2011 1:35 PM ()

Also, Expert F# Chapter 13 has an example of an AsyncRequestGate type that wraps a semaphore.

Robert Pickering has used this code here to write a great sample here:

[link:strangelights.com]

By on 1/13/2011 2:12 AM ()

Thanks everyone for your valuable replies! Those examples are exactly what i needed and should be a great start :D

By on 1/14/2011 10:48 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper