Last active
December 20, 2015 01:59
-
-
Save toburger/6053133 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
(* see: http://stackoverflow.com/questions/6219726/throttled-async-download-in-f *) | |
open System | |
type ThrottlingAgentMessage<'a> = | |
| AddJob of Async<'a> * AsyncReplyChannel<'a> | |
| CompletedJob of 'a * AsyncReplyChannel<'a> | |
| Stop | |
type ThrottlingAgent<'a>(limit) = | |
let agent = MailboxProcessor<ThrottlingAgentMessage<'a>>.Start(fun agent -> | |
let rec loop jobs count = async { | |
let! msg = agent.Receive() | |
match msg with | |
| AddJob(job, reply) -> | |
if count < limit then | |
return! work ((job, reply)::jobs) count | |
else | |
return! loop ((job, reply)::jobs) count | |
| CompletedJob(result, reply) -> | |
reply.Reply result | |
return! work jobs (count-1) | |
| Stop -> return () | |
} | |
and work jobs count = async { | |
match jobs with | |
| [] -> return! loop jobs count | |
| (job, reply)::jobs -> | |
async { | |
let! result = job | |
agent.Post(CompletedJob(result, reply)) | |
} |> Async.Start | |
return! loop jobs (count + 1) | |
} | |
loop [] 0 | |
) | |
member __.AddJob(job) = agent.PostAndAsyncReply(fun rep -> AddJob(job, rep)) | |
member __.Stop() = agent.Post(Stop) | |
static member RunJobs limit jobs = | |
let agent = ThrottlingAgent<'a>(limit) | |
let res = | |
jobs | |
|> Seq.map agent.AddJob | |
|> Async.Parallel | |
|> Async.RunSynchronously | |
agent.Stop() | |
res |
Author
toburger
commented
Jul 22, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment