Lecture 13 — Events and asynchronous computations
1 · Synchronous, asynchronous, concurrent, parallel, reactive
What do the following mean?
-
Synchronous. The caller starts an operation and waits until it has
finished. Everything we have written so far is synchronous.
-
Asynchronous. The caller starts an operation and carries on. The
result is delivered later, to a function that was handed over for
that purpose.
-
Concurrency. Several computations are in progress during the same
period of time. They may take turns on a single processor.
-
Parallelism. Several computations run at the same instant, on
several processors.
-
Reactive. The program does not decide when things happen. It
responds to events as they arrive.
Why should we care?
Scalability, throughput, responsiveness, ...
If you are used to synchronous programming, then you need to think
differently when dealing with concurrency, parallelism, asynchronous
and reactive programs.
The main reason is nondeterminism: the same program can do things
in a different order on each run.
How to use this script
Much of what this lecture shows depends on timers, threads, the network
or the file system. Loading this script as a whole only defines things
and prints the examples whose output is the same on every run.
Everything else is shown as a session of F# Interactive, like this:
> 1 + 1;;
val it: int = 2
|
Load the script, then send the lines after > yourself, in the order
in which they appear. The output shown is that of one run. Yours will
differ in the details: other numbers, other thread ids, another order.
The echo val it: unit = () is left out of the sessions.
2 · Events and callbacks
An event is a representation of something happening.
This something could be a click of a mouse button. We say that clicking
the mouse triggers (or fires) the event.
The important part is that we can listen to these mouse click events
by registering a callback for these events.
A callback is a function of type X -> unit where X is determined by
the event type. (It is sometimes also called an event handler.)
A callback is a description of what to do when the event fires. Recall
continuations (Lecture 8): a continuation also says what to do next,
once a result is there.
Events as first-class citizens
The examples are based on code examples from the book Expert F# 4.0
by Don Syme, Adam Granicz and Antonio Cisternino.
In the following example an event represents a change to a file in a
directory. The directory is created under the system's temporary path.
open System
open System.IO
let watchDir = Path.Combine (Path.GetTempPath (), "itt8060-lecture13")
Directory.CreateDirectory watchDir |> ignore
let watcher = new FileSystemWatcher (watchDir)
// watcher.Changed is an event
// we listen to this event by adding a callback/handler
watcher.Changed.Add (fun args -> printfn "File %s was changed!" args.Name)
Note that when an event triggers, the callbacks are called in the
order they were added.
You can add and later remove handlers using AddHandler and
RemoveHandler.
let handler =
FileSystemEventHandler (fun _ args -> printfn "File %s was created!" args.Name)
watcher.Created.AddHandler handler
watcher.Created.RemoveHandler handler
A watcher raises no events until EnableRaisingEvents is set. In the
session below we set it and write to a file in the directory. Then we
add handler, write to a new file, remove handler again and write to
a third file. In the end we dispose the watcher.
> watcher.EnableRaisingEvents <- true;;
> File.WriteAllText (Path.Combine (watchDir, "a.txt"), "hello");;
File a.txt was changed!
> File.AppendAllText (Path.Combine (watchDir, "a.txt"), " again");;
File a.txt was changed!
> watcher.Created.AddHandler handler;;
> File.WriteAllText (Path.Combine (watchDir, "b.txt"), "hello");;
File b.txt was created!
File b.txt was changed!
> watcher.Created.RemoveHandler handler;;
> File.WriteAllText (Path.Combine (watchDir, "c.txt"), "hello");;
File c.txt was changed!
> watcher.Dispose ();;
> File.WriteAllText (Path.Combine (watchDir, "d.txt"), "hello");;
|
Writing to a new file raises both Created and Changed. The
callbacks run on another thread, a moment after the write. After
Dispose the watcher reports nothing.
You can also change the files of that directory by hand, in an editor
or a file manager, and watch the callbacks being called.
3 · Defining an event
An event of our own is a value of type Event<'T>. It has two sides.
Publish is what the listeners get: they add callbacks to it.
Trigger fires the event with a value of type 'T.
let manual = Event<int> ()
manual.Publish.Add (fun n -> printfn "first callback: %d" n)
manual.Publish.Add (fun n -> printfn "second callback: %d" n)
printfn "before the trigger"
manual.Trigger 1
printfn "after the trigger"
before the trigger
first callback: 1
second callback: 1
after the trigger
|
Trigger calls the callbacks one after the other, in the order they
were added, and returns when the last one has returned.
An event fired by a timer
The following class has an event that fires at random intervals. It
uses three features of F# classes:
type RandomTicker (approxInterval) =
let timer = new Timers.Timer ()
let rnd = Random ()
// our event
let tickEvent = Event<int> ()
let chooseInterval () : int =
approxInterval + approxInterval / 4 - rnd.Next (approxInterval / 2)
do timer.Interval <- chooseInterval ()
do timer.Elapsed.Add (fun _ ->
let interval = chooseInterval ()
tickEvent.Trigger interval
timer.Interval <- interval)
member _.RandomTick = tickEvent.Publish
member _.Start () = timer.Start ()
member _.Stop () = timer.Stop ()
interface IDisposable with
member _.Dispose () = timer.Dispose ()
The timer's own event, timer.Elapsed, gets a callback that triggers
our event. The class publishes the event as RandomTick.
Create the ticker and add a callback:
let rt = new RandomTicker (1000)
rt.RandomTick.Add (fun nextInterval -> printfn "Tick, next = %A" nextInterval)
Start the ticker, wait, and stop it:
> rt.Start ();;
Tick, next = 832
Tick, next = 1195
Tick, next = 975
Tick, next = 1228
Tick, next = 1212
> rt.Stop ();;
|
4 · Events as first-class values
An event is a value. It can be passed to a function, and the functions
of the Event module make new events from existing ones. Here is an
event that fires only when manual fires with an even number:
manual.Publish
|> Event.filter (fun n -> n % 2 = 0)
|> Event.add (fun n -> printfn "Even: %d" n)
manual.Trigger 2
manual.Trigger 3
first callback: 2
second callback: 2
Even: 2
first callback: 3
second callback: 3
|
The two callbacks of section 3 are still there. The third callback
listens to the filtered event.
The same for the ticker, this time as a session. The first input adds
the filtered callback to rt:
> rt.RandomTick
|> Event.filter (fun interval -> interval % 2 = 0)
|> Event.add (fun i -> printfn "Even: %d" i);;
> rt.Start ();;
Tick, next = 818
Even: 818
Tick, next = 1050
Even: 1050
Tick, next = 993
Tick, next = 979
Tick, next = 994
Even: 994
> rt.Stop ();;
> (rt :> IDisposable).Dispose ();;
|
Dispose is a member of the interface IDisposable. F# implements
interface members explicitly, so rt has to be cast to the interface
before Dispose can be called. (A use binding does this for us.)
We can work with event streams in a compositional way. (The types are
simplified here.)
Event.choose : ('T -> 'U option) -> IEvent<'T> -> IEvent<'U>
Event.filter : ('T -> bool) -> IEvent<'T> -> IEvent<'T>
Event.scan : ('U -> 'T -> 'U) -> 'U -> IEvent<'T> -> IEvent<'U>
Event.map : ('T -> 'U) -> IEvent<'T> -> IEvent<'U>
Event.partition : ('T -> bool) -> IEvent<'T> -> IEvent<'T> * IEvent<'T>
|
5 · Observables
Events give us a nice way to work with and express callback
structures.
A more advanced framework for working with such things (events and
more) is called observables: the interfaces System.IObservable<'T>
and System.IObserver<'T>.
F# includes the FSharp.Control.Observable module, which contains the
basics. They are similar to what we have seen for events. Events in F#
are also observables, as they implement the required interface.
A lot more is covered by Reactive Extensions (Rx), which is available
for F# as the package FSharp.Control.Reactive. The following is not
part of this script, because it needs the package:
#r "nuget: FSharp.Control.Reactive"
open FSharp.Control.Reactive
open FSharp.Control.Reactive.Builders
let rec f x =
observe {
yield x
if x < 10000 then
yield! f (x + 1)
}
f 5 |> Observable.subscribe (fun x -> printfn "%i" x)
let query =
rxquery {
for i in f 5000 do
groupBy (i % 3) into grp
yield grp.Key
}
query |> Observable.subscribe (fun x -> printfn "%A" x)
|
The first subscription prints the numbers from 5 to 10000. The second
prints 2, 0 and 1: the keys of the three groups, each when its
first element arrives.
6 · Pull and push
Typical collections are pull-based: we ask the collection to give us
an element. When we are done working with it, we ask the collection
for the next element. We pull elements from the collection one by one
and exactly when we want them. This is what the enumerators of
Lecture 12 do: the consumer calls MoveNext and reads Current.
For a push-based collection we tell the collection that we are
interested in its items. When something gets added to the collection,
then the collection pushes the new item to us. Importantly, we as the
clients of that collection are not in control over when something is
added to the collection: we process the item when it is pushed to us.
Getters and setters
type Getter<'a> = unit -> 'a
type Setter<'a> = 'a -> unit
|
What is an enumerator of values of type 'a (or an iterator)?
It is something that will give us a value of type 'a when we ask for
it. It can be seen as a getter of 'a: a function that applied to an
argument of type unit gives us an 'a.
An enumerator is a Getter<'a>
|
What is an enumerable? Something is an enumerable when we can ask for
its enumerator. That is, a function that applied to an argument gives
us an enumerator.
An enumerable is a Getter<Getter<'a>>
|
When we unfold the definition we see that an enumerable is
The essence of pull-based collections is the above type. For a
pull-based collection we can ask for its enumerator, which in turn
allows us to pull its elements.
What about setters? What about push-based collections?
If we turn the arrows around, we get
which is also
For push-based collections the important part is that we can register
a callback (a function of type 'a -> unit) with the collection.
Enumerable -- Enumerator a pull-based collection gives us a way to get the elements
Observable -- Observer a push-based collection asks for a callback that handles an element
|
There is a lot more to this. For an (entertaining) introduction watch
the presentation by Erik Meijer, who is one of the people behind LINQ
and Rx among other things:
https://www.youtube.com/watch?v=sTSQlYX5DU0.
7 · Combining observables
Observable.choose : ('a -> 'b option) -> IObservable<'a> -> IObservable<'b>
Observable.filter : ('a -> bool) -> IObservable<'a> -> IObservable<'a>
Observable.map : ('a -> 'b) -> IObservable<'a> -> IObservable<'b>
Observable.scan : ('b -> 'a -> 'b) -> 'b -> IObservable<'a> -> IObservable<'b>
Observable.partition : ('a -> bool) -> IObservable<'a> -> IObservable<'a> * IObservable<'a>
Observable.split : ('a -> Choice<'b,'c>) -> IObservable<'a> -> IObservable<'b> * IObservable<'c>
Observable.merge : IObservable<'a> -> IObservable<'a> -> IObservable<'a>
Observable.pairwise : IObservable<'a> -> IObservable<'a * 'a>
Observable.add : ('a -> unit) -> IObservable<'a> -> unit
Observable.subscribe : ('a -> unit) -> IObservable<'a> -> IDisposable
|
We take two events as sources: one of numbers and one of strings. For
now we trigger them by hand.
let ticks = Event<int> ()
let words = Event<string> ()
let evens =
ticks.Publish
|> Observable.filter (fun i -> i % 2 = 0)
let (evs, odds) =
ticks.Publish
|> Observable.partition (fun i -> i % 2 = 0)
let soEven =
evs
|> Observable.map (fun i -> i * 10)
|> Observable.map (fun i -> sprintf "Even: %d" i)
let strCount =
words.Publish
|> Observable.scan (fun acc _ -> acc + 1) 0
|> Observable.filter (fun i -> i % 5 = 0)
let merged = Observable.merge evs strCount
strCount counts the strings and lets every fifth count through.
merged carries the even numbers and those counts.
Nothing has happened so far: an observable does nothing until somebody
subscribes to it. Observable.subscribe adds a callback and returns an
IDisposable. Disposing it ends the subscription.
let obsStr = soEven |> Observable.subscribe (fun s -> printfn "%s" s)
let obs1 = merged |> Observable.subscribe (fun i -> printfn "Obs1: %d" i)
let obs2 = merged |> Observable.subscribe (fun i -> printfn "Obs2: %d" i)
An even number reaches all three subscribers, an odd number none:
ticks.Trigger 1012
ticks.Trigger 987
Even: 10120
Obs1: 1012
Obs2: 1012
|
Five strings give one count:
for w in ["a"; "b"; "c"; "d"; "e"] do
words.Trigger w
After obs1.Dispose () only the other subscribers are called:
obs1.Dispose ()
ticks.Trigger 1100
obs2.Dispose ()
obsStr.Dispose ()
With all three subscriptions disposed, ticks.Trigger 1200 prints
nothing.
The tickers as sources
A second class of tickers produces strings:
type StringTicker (approxInterval) =
let timer = new Timers.Timer ()
let rnd = Random ()
// our event
let tickEvent = Event<string> ()
let chooseInterval () : int =
approxInterval + approxInterval / 4 - rnd.Next (approxInterval / 2)
do timer.Interval <- chooseInterval ()
do timer.Elapsed.Add (fun _ ->
let interval = chooseInterval ()
tickEvent.Trigger (sprintf "<%d>" interval)
timer.Interval <- interval)
member _.RandomTick = tickEvent.Publish
member _.Start () = timer.Start ()
member _.Stop () = timer.Stop ()
interface IDisposable with
member _.Dispose () = timer.Dispose ()
We make a new number ticker and a string ticker, and let them trigger
ticks and words. The pipelines above stay as they are: they do not
know where the values come from.
let rt2 = new RandomTicker (1000)
let st = new StringTicker (3000)
rt2.RandomTick.Add ticks.Trigger
st.RandomTick.Add words.Trigger
The string ticker fires about every three seconds, so a count arrives
after about fifteen seconds:
> let live = merged |> Observable.subscribe (fun i -> printfn "Live: %d" i);;
> rt2.Start ();;
> st.Start ();;
Live: 752
Live: 1174
Live: 768
Live: 780
Live: 1168
Live: 5
Live: 1060
Live: 1040
> rt2.Stop ();;
> st.Stop ();;
> live.Dispose ();;
> (rt2 :> IDisposable).Dispose ();;
> (st :> IDisposable).Dispose ();;
|
8 · Asynchronous computations
Blocking and non-blocking
A blocking call holds on to its thread until the result is there,
even when all it does is wait for a disk or for the network. A
non-blocking call starts the operation and gives the thread back.
The rest of the work is done when the result arrives.
Written by hand, non-blocking code is a chain of callbacks. There is a
set of tools in F# for structuring non-blocking programs in a (more)
familiar way that avoids using explicit callbacks: async computation
expressions.
Lecture 11 introduced async { } and task { } as computation
expressions, and showed that async delays its body while task
starts it at once. This lecture is about what the two are for.
From Microsoft Learn,
Async programming in F#:
In F#, asynchronous programming is centered around two core concepts:
async computations and tasks.
-
The
Async<'T> type with async { } expressions, which represents
a composable asynchronous computation that can be started to form a
task.
-
The
Task<'T> type, with task { } expressions, which represents
an executing .NET task.
In general, you should consider using task {…} over async {…} in
new code if you're interoperating with .NET libraries that use tasks,
and if you don't rely on asynchronous code tailcalls or implicit
cancellation token propagation.
Downloading a web page, blocking
The thread that calls downloadSync waits for the response and then
for the whole text.
open System.Net.Http
// the blocking way
let downloadSync (url : string) =
use client = new HttpClient ()
use request = new HttpRequestMessage (HttpMethod.Get, url)
use response = client.Send request
let stream = response.Content.ReadAsStream ()
use reader = new StreamReader (stream)
reader.ReadToEnd ()
In the sessions of this section we look at the length of the text, not
at the text itself:
> downloadSync "https://www.postimees.ee" |> String.length;;
val it: int = 178355
|
Downloading a web page with async
Async.AwaitTask turns a .NET task into an Async:
let readToEndAsync (reader : StreamReader) =
Async.AwaitTask (reader.ReadToEndAsync ())
In an async { } expression, let! waits for an asynchronous
computation without blocking a thread:
let downloadAsync (url : string) =
async {
let client = new HttpClient ()
let! response = client.GetAsync url |> Async.AwaitTask
response.EnsureSuccessStatusCode () |> ignore
let! content = response.Content.ReadAsStringAsync () |> Async.AwaitTask
return content
}
let result = downloadAsync "https://www.postimees.ee"
result has type Async<string>. Nothing has been downloaded: an
Async is a description of a computation, and it runs when we start
it. Async.RunSynchronously starts it and waits for the result.
> result |> Async.RunSynchronously |> String.length;;
val it: int = 178355
|
Which thread does the work? The following version prints the id of the
current thread at three points.
let downloadAsyncVerbose (url : string) =
async {
let threadId = Threading.Thread.CurrentThread.ManagedThreadId
printfn "Creating request for %s with thread %i" url threadId
let client = new HttpClient ()
let! response = client.GetAsync url |> Async.AwaitTask
response.EnsureSuccessStatusCode () |> ignore
let threadId = Threading.Thread.CurrentThread.ManagedThreadId
printfn "Getting response stream for %s with thread %i" url threadId
let! content = response.Content.ReadAsStringAsync () |> Async.AwaitTask
let threadId = Threading.Thread.CurrentThread.ManagedThreadId
printfn "Reading response for %s with thread %i" url threadId
return content
}
let aresult = downloadAsyncVerbose "https://www.postimees.ee"
> aresult |> Async.RunSynchronously |> String.length;;
Creating request for https://www.postimees.ee with thread 16
Getting response stream for https://www.postimees.ee with thread 14
Reading response for https://www.postimees.ee with thread 14
val it: int = 178355
|
The computation does not stay on one thread. While it waits at a
let! it holds no thread at all, and it continues on whichever thread
is free when the result arrives.
Tasks
The task { } syntax was introduced in F# 6.0. Previously a similar
result was achieved with async.
Note that you do not want to create an HttpClient for every request.
You may want to reuse it for efficiency. The following function takes
the client as an argument.
let getHttp (client : HttpClient) (url : string) =
task {
let! response = client.GetAsync url
response.EnsureSuccessStatusCode () |> ignore
let! content = response.Content.ReadAsStringAsync ()
return content
}
Unlike async expressions, task expressions do not implicitly pass a
cancellation token and don't implicitly perform cancellation checks.
Unlike async expressions, task expressions do not support tailcalls.
let client = new HttpClient ()
Calling getHttp starts the download at once (Lecture 11). x.Result
waits for the task to finish.
> let x = getHttp client "https://www.err.ee";;
val x: Threading.Tasks.Task<string>
> x.Result |> String.length;;
val it: int = 360616
|
Several downloads in parallel
Async.Parallel makes one asynchronous computation out of several. Its
result is the array of their results.
let museums =
[ "Kumu", "https://kumu.ekm.ee"
"ERM", "https://www.erm.ee"
"Vabamu", "https://www.vabamu.ee"
"Kiasma", "https://www.kiasma.fi" ]
let downloads =
Async.Parallel [ for _, url in museums -> downloadAsyncVerbose url ]
> downloads |> Async.RunSynchronously |> Array.map String.length;;
Creating request for https://kumu.ekm.ee with thread Creating request for 14https://www.erm.ee
with thread 22
Creating request for https://www.vabamu.ee with thread 16
Creating request for https://www.kiasma.fi with thread 21
Getting response stream for https://www.erm.ee with thread 21
Reading response for https://www.erm.ee with thread 21
Getting response stream for https://www.vabamu.ee with thread 21
Reading response for https://www.vabamu.ee with thread 21
Getting response stream for https://kumu.ekm.ee with thread 14
Reading response for https://kumu.ekm.ee with thread 14
Getting response stream for https://www.kiasma.fi with thread 14
Reading response for https://www.kiasma.fi with thread 14
val it: int array = [|565806; 280023; 117269; 158564|]
|
The four computations start on different threads at almost the same
time. Two of them even printed at the same moment, and their lines ran
into each other: the console is shared, too. All four downloads are
then under way at once. The responses arrive in some order, but the
lengths in the result are in the order of museums.
9 · An async from a callback, and what async { } means
An API that works with callbacks can be turned into an Async with
Async.FromContinuations. It hands us three continuations: one to call
with the result, one for an exception and one for cancellation.
Here the callback is that of a timer that fires once. When it fires, we
call the success continuation.
let sleepAsync (time : float) =
Async.FromContinuations (fun (successCont, exnCont, cancelCont) ->
let timer = new Timers.Timer (time, AutoReset = false)
timer.Elapsed.Add (fun _ -> successCont ())
timer.Start ())
let timerTest =
async {
printfn "Starting ..."
do! sleepAsync 1000.0
//failwith "error"
printfn "Finished."
}
printfn "timerTest is defined."
Async.RunSynchronously timerTest
timerTest is defined.
Starting ...
Finished.
|
Defining timerTest prints nothing. Running it prints the first
message, waits a second without holding a thread, and prints the
second message when the timer calls the continuation.
What async { } means
An async { } expression is translated into calls of the methods of
the builder async, by the rules of Lecture 11. Here is a download
written with the syntax, and the same computation written with the
methods:
let kumu : Async<string> =
async {
let! response = client.GetAsync "https://kumu.ekm.ee" |> Async.AwaitTask
let! html = response.Content.ReadAsStringAsync () |> Async.AwaitTask
return html
}
let kumu' : Async<string> =
async.Delay (fun () ->
async.Bind (client.GetAsync "https://kumu.ekm.ee" |> Async.AwaitTask, fun response ->
async.Bind (response.Content.ReadAsStringAsync () |> Async.AwaitTask, fun html ->
async.Return html)))
Each let! becomes a Bind. Its second argument is a function that
takes the result: the continuation, that is, the callback. Delay
keeps the whole computation from starting before it is run.
> Async.RunSynchronously kumu |> String.length;;
val it: int = 565806
> Async.RunSynchronously kumu' |> String.length;;
val it: int = 565806
|
10 · Running, combining and failing
Async.RunSynchronously : Async<'a> -> 'a
Async.Start : Async<unit> -> unit
Async.StartAsTask : Async<'a> -> Threading.Tasks.Task<'a>
Async.StartImmediate : Async<unit> -> unit
Async.StartImmediateAsTask : Async<'a> -> Threading.Tasks.Task<'a>
Async.Choice : seq<Async<'a option>> -> Async<'a option>
Async.Parallel : seq<Async<'a>> -> Async<'a array>
Async.Ignore : Async<'a> -> Async<unit>
Async.Catch : Async<'a> -> Async<Choice<'a, exn>>
|
Async.Parallel does not need the network. Here it combines five
small computations. The results are in the order of the computations:
let squares =
Async.Parallel [ for i in 1 .. 5 -> async { return i * i } ]
|> Async.RunSynchronously
Failing
An exception in an asynchronous computation is thrown where the
computation is run.
let failingAsync = async { do failwith "fail" }
> Async.RunSynchronously failingAsync;;
System.Exception: fail
at ...
Stopped due to error
|
When several computations run in parallel and fail, we see one of the
exceptions:
let failingAsyncs =
[ async { do failwith "fail A" }
async { do failwith "fail B" } ]
> Async.RunSynchronously (Async.Parallel failingAsyncs);;
System.Exception: fail A
at ...
Stopped due to error
|
Async.Catch turns a computation that may fail into one that returns
a Choice: the result, or the exception.
let caught =
match Async.RunSynchronously (Async.Catch failingAsync) with
| Choice1Of2 () -> "finished"
| Choice2Of2 e -> "caught: " + e.Message
11 · Agents
An agent is an asynchronous computation with a mailbox. It receives
its messages one at a time, in a loop, and the state of the agent is
the argument of that loop. Nothing outside the agent can touch the
state: other code can only post messages. An agent is a state machine.
In F# an agent is a MailboxProcessor.
type Agent<'T> = MailboxProcessor<'T>
let counter =
new Agent<_> (fun inbox ->
// this n is the current state of the machine
let rec loop n =
async {
printfn "n = %d, waiting..." n
let! msg = inbox.Receive ()
return! loop (n + msg)
}
loop 0)
inbox.Receive () waits for the next message without holding a
thread. The agent does nothing until it is started:
> counter.Start ();;
n = 0, waiting...
> counter.Post 1;;
n = 1, waiting...
> counter.Post 2;;
n = 3, waiting...
> counter.Post 1;;
n = 4, waiting...
|
Post returns at once. The agent prints from its own computation, a
moment later.
The next machine has two states, each a function of its own. It is
either accepting or rejecting.
let accept =
new Agent<_> (fun inbox ->
// Machine is either in accepting or rejecting state
let rec accept () =
async {
let! msg = inbox.Receive ()
if msg % 5 = 0 then
return! reject ()
else
printfn "Accept!"
return! accept ()
}
and reject () =
async {
let! msg = inbox.Receive ()
if msg % 7 = 0 then
return! accept ()
else
return! reject ()
}
accept ())
A multiple of 5 sends the machine into the rejecting state, and a
multiple of 7 brings it back:
> accept.Start ();;
> accept.Post 1;;
Accept!
> accept.Post 7;;
Accept!
> accept.Post 5;;
> accept.Post 3;;
> accept.Post 14;;
> accept.Post 3;;
Accept!
|
Replies
An agent can answer. The message then carries a reply channel, and the
sender waits for the reply with PostAndReply.
/// The type of messages for the agent
type CounterMessage =
| Increment of int
| Fetch of AsyncReplyChannel<int>
| Stop
type CountingAgent () =
let counter =
MailboxProcessor.Start (fun inbox ->
// The states of the message-processing state machine...
let rec loop n =
async {
let! msg = inbox.Receive ()
match msg with
| Increment m ->
// increment and continue...
return! loop (n + m)
| Stop ->
// exit
return ()
| Fetch replyChannel ->
// post response to reply channel and continue
do replyChannel.Reply n
return! loop n
}
// The initial state of the message-processing state machine...
loop 0)
member _.Increment n = counter.Post (Increment n)
member _.Stop () = counter.Post Stop
member _.Fetch () = counter.PostAndReply (fun replyChannel -> Fetch replyChannel)
The messages of one sender are handled in the order in which they were
posted, so a Fetch sees every Increment posted before it:
let counting = CountingAgent ()
counting.Increment 1
let fetched1 = counting.Fetch ()
counting.Increment 2
let fetched2 = counting.Fetch ()
counting.Stop ()
After Stop the loop has ended and nobody reads the mailbox any more.
A Fetch sent now would wait for its reply for ever.
Scanning the mailbox
Scan looks through the mailbox for the first message the given
function accepts. Messages it does not accept stay in the mailbox.
type Message =
| Message1
| Message2 of int
| Message3 of string
let agent =
MailboxProcessor.Start (fun inbox ->
let rec loop () =
inbox.Scan (function
| Message1 ->
Some (async {
do printfn "message 1!"
return! loop ()
})
| Message2 _ ->
Some (async {
do printfn "message 2!"
return! loop ()
})
| Message3 _ ->
None)
loop ())
> agent.Post Message1;;
message 1!
> agent.Post (Message2 100);;
message 2!
> agent.Post (Message3 "abc");;
> agent.Post (Message2 100);;
message 2!
> agent.CurrentQueueLength;;
val it: int = 1
|
The Message3 is still in the mailbox.
12 · Shared-memory concurrency
An agent keeps its state to itself. The alternative is state that
several computations share. Here is a pair that can be updated:
type MutablePair<'T, 'U> (x : 'T, y : 'U) =
let mutable currentX = x
let mutable currentY = y
member _.Value = (currentX, currentY)
member _.Update (x, y) =
// Race condition: This pair of updates is not atomic
currentX <- x
currentY <- y
let p = MutablePair<_, _> (1, 2)
We start two computations that update the pair for ever, one to
(10, 10) and one to (20, 20), and then read the pair many times.
The two loops never end. They keep two processors busy until F#
Interactive is reset, so reset it after this session.
> Async.Start (async { do (while true do p.Update (10, 10)) });;
> Async.Start (async { do (while true do p.Update (20, 20)) });;
> [ for _ in 1 .. 1000000 -> p.Value ] |> List.distinct;;
val it: (int * int) list = [(20, 20); (10, 10); (20, 10); (10, 20)]
|
The pair is never set to (10, 20) or (20, 10), and yet we read
them: the reader, or the other writer, came between the two
assignments of an Update.
Locks
A lock lets one computation at a time into a critical section. F# has
a function lock for this. The following definition shows how it
works (and shadows it):
open System.Threading
let lock (lockobj : obj) f =
Monitor.Enter lockobj
try
f ()
finally
Monitor.Exit lockobj
In a fresh session, every update and every read takes the lock of p:
> Async.Start (async { do (while true do lock p (fun () -> p.Update (10, 10))) });;
> Async.Start (async { do (while true do lock p (fun () -> p.Update (20, 20))) });;
> [ for _ in 1 .. 100000 -> lock p (fun () -> p.Value) ] |> List.distinct;;
val it: (int * int) list = [(10, 10); (20, 20)]
|
Again, reset F# Interactive afterwards.
A reader–writer lock
With one lock, readers also wait for each other, although reading
together is harmless. A reader–writer lock lets many readers in at the
same time, but a writer only alone.
(The class used here, ReaderWriterLock, is the original one. For new
code the .NET documentation recommends its successor,
ReaderWriterLockSlim.)
let readLock (rwlock : ReaderWriterLock) f =
rwlock.AcquireReaderLock Timeout.Infinite
try
f ()
finally
rwlock.ReleaseReaderLock ()
let writeLock (rwlock : ReaderWriterLock) f =
rwlock.AcquireWriterLock Timeout.Infinite
try
f ()
Thread.MemoryBarrier ()
finally
rwlock.ReleaseWriterLock ()
type LockedPair<'T, 'U> (x : 'T, y : 'U) =
let mutable currentX = x
let mutable currentY = y
let rwlock = ReaderWriterLock ()
member _.Value =
readLock rwlock (fun () -> (currentX, currentY))
member _.Update (x, y) =
writeLock rwlock (fun () ->
currentX <- x
currentY <- y)
The pair is used as before:
let lp = LockedPair<_, _> (1, 2)
lp.Update (3, 4)
let lpValue = lp.Value
13 · Memoization
Sections 13, 14 and 15 are samples to study on your own. Each says
what it shows, how to run it and what to look for.
What this sample shows. Memoization: a function that remembers the
results it has computed, in a mutable dictionary shared by all its
calls. This is shared state, as in section 12, hidden inside a
function. The sample is from
fssnip.net/8P.
How to run it. Load the script and send the lines of the session
below. #time "on" makes F# Interactive print the time each input
takes.
What to look for. Which calls are slow and which return at once.
A slow function:
let rec fibs n =
if n < 1 then 1
else fibs (n - 1) + fibs (n - 2)
open System.Collections.Generic
/// The function creates a function that calls the argument 'f'
/// only once and stores the result in a mutable dictionary (cache)
/// Repeated calls to the resulting function return cached values.
let memoize f =
// Create (mutable) cache that is used for storing results of
// for function arguments that were already calculated.
let cache = Dictionary<_, _> ()
(fun x ->
// The returned function first performs a cache lookup
let succ, v = cache.TryGetValue x
if succ then v else
// If value was not found, calculate & cache it
let v = f x
cache.Add (x, v)
v)
// Notice this is not optimal for fibs!!!
// We are just caching results.
let memfibs = memoize fibs
memfibs remembers the result for each argument it has been called
with. The recursive calls inside fibs do not go through the cache.
In the following version they do: the recursive calls are made to the
memoized function, so previously calculated values are retrieved from
the cache.
// Warning 40: fibsm is a value that refers to itself, which is checked
// at run time. That is not an issue here.
#nowarn "40"
let rec fibsm =
memoize (fun n ->
if n < 1 then 1
else fibsm (n - 1) + fibsm (n - 2))
let fibsm44 = fibsm 44
> #time "on";;
> fibs 41;;
Real: 00:00:00.753, CPU: 00:00:00.375, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 433494437
> memfibs 44;;
Real: 00:00:02.761, CPU: 00:00:01.187, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 1836311903
> memfibs 44;;
Real: 00:00:00.001, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 1836311903
> memfibs 43;;
Real: 00:00:01.742, CPU: 00:00:00.640, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 1134903170
> fibsm 44;;
Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 1836311903
> fibsm 42;;
Real: 00:00:00.000, CPU: 00:00:00.000, GC gen0: 0, gen1: 0, gen2: 0
val it: int = 701408733
> #time "off";;
|
The second memfibs 44 comes from the cache. memfibs 43 is slow
again: only the results of the outermost calls were cached. fibsm
caches every intermediate result. (Its first call was made when the
script was loaded, for the value shown above, so here it only looks the
result up. That first call took no noticeable time either.)
14 · Image processing
What this sample shows. The same work done twice: synchronously,
one image after the other, and as asynchronous computations combined
with Async.Parallel (sections 8 and 10). Each image is read from a
file, transformed by a computation that keeps a processor busy, and
written to another file.
How to run it. Load the script and send the lines of the session
below, in order. makeImageFiles () writes the image files (about 50
MB) into a directory under the system's temporary path. The last line
of the session removes that directory again.
What to look for. #time prints two times: Real is the time that
passed, CPU is the processor time used, added up over all
processors. Compare both for the two versions.
let numImages = 200
let size = 512
let numPixels = size * size
let imageDir = Path.Combine (Path.GetTempPath (), "itt8060-lecture13-images")
let imageFile (i : int) (extension : string) =
Path.Combine (imageDir, sprintf "Image%d.%s" i extension)
let makeImageFiles () =
printfn "making %d %dx%d images... " numImages size size
Directory.CreateDirectory imageDir |> ignore
let pixels = Array.init numPixels (fun i -> byte i)
for i = 1 to numImages do
File.WriteAllBytes (imageFile i "tmp", pixels)
printfn "done."
let processImageRepeats = 500
let transformImage (pixels, imageNum) =
printfn "transformImage %d" imageNum
// Perform a CPU-intensive operation on the image.
for i in 1 .. processImageRepeats do
pixels |> Array.map (fun b -> b + 1uy) |> ignore
pixels |> Array.map (fun b -> b + 1uy)
let processImageSync i =
use inStream = File.OpenRead (imageFile i "tmp")
let pixels = Array.zeroCreate numPixels
let nPixels = inStream.Read (pixels, 0, numPixels)
let pixels' = transformImage (pixels, i)
use outStream = File.OpenWrite (imageFile i "done")
outStream.Write (pixels', 0, nPixels)
let processImagesSync () =
printfn "processImagesSync..."
for i in 1 .. numImages do
processImageSync i
let processImageAsync i =
async {
use inStream = File.OpenRead (imageFile i "tmp")
let! pixels = inStream.AsyncRead numPixels
let pixels' = transformImage (pixels, i)
use outStream = File.OpenWrite (imageFile i "done")
do! outStream.AsyncWrite pixels'
}
let processImagesAsync () =
printfn "processImagesAsync..."
let tasks = [ for i in 1 .. numImages -> processImageAsync i ]
Async.RunSynchronously (Async.Parallel tasks) |> ignore
printfn "processImagesAsync finished!"
> makeImageFiles ();;
making 200 512x512 images...
done.
> #time "on";;
> processImagesSync ();;
processImagesSync...
transformImage 1
transformImage 2
transformImage 3
...
transformImage 200
Real: 00:00:24.585, CPU: 00:00:11.343, GC gen0: 499, gen1: 499, gen2: 499
> processImagesAsync ();;
processImagesAsync...
transformImage 9
transformImage 5
transformImage 13
transformImage 17
transformImage 19
transformImage 7
...
processImagesAsync finished!
Real: 00:00:06.244, CPU: 00:00:14.093, GC gen0: 157, gen1: 157, gen2: 157
> #time "off";;
> Directory.Delete (imageDir, true);;
|
In the synchronous run the images are transformed in order, by one
thread. In the asynchronous run they are transformed in whatever order
the threads get to them. About as much processor time is used, but it
is spread over several processors (this machine has 20), so much less
time passes: 6 seconds instead of 25.
Three ways to start an async
The following computation sleeps for three seconds and then prints.
let delay =
async {
do! Async.Sleep 3000
printfn "Done sleeping"
}
> Async.Start delay;;
val it: unit = ()
Done sleeping
> Async.RunSynchronously delay;;
Done sleeping
val it: unit = ()
> Async.StartImmediate delay;;
val it: unit = ()
Done sleeping
|
Async.Start and Async.StartImmediate return at once, and the
message appears three seconds later. Async.RunSynchronously returns
after the message. Async.StartImmediate runs the computation on the
current thread up to its first wait; Async.Start hands all of it to
the thread pool.
15 · A web crawler
What this sample shows. An agent (section 11), asynchronous web
requests (section 8) and a gate working together. The agent
urlCollector receives addresses. For each address it has not seen,
it starts an asynchronous computation that downloads the page and
posts the links found there back to the agent. A gate lets at most
five requests be under way at a time. The crawler stops after
maxPages addresses.
How to run it. Load the script and post one address to the agent,
as in the session below. This needs the network.
What to look for. The pages do not finish in the order in which
they were started, and the crawler stops by itself.
open System.Text.RegularExpressions
let maxPages = 50
let linkPat = "href=\s*\"[^\"h]*(https?://[^&\"]*)\""
let getLinks (txt : string) =
[ for m in Regex.Matches (txt, linkPat) -> m.Groups[1].Value ]
let sampleLinks =
getLinks "<a href=\"https://example.org/a\">a</a> <a href=\"/local\">b</a>"
["https://example.org/a"]
|
Only links with a full address are followed.
// A type that helps limit the number of active web requests
type RequestGate (n : int) =
let semaphore = new Semaphore (initialCount = n, maximumCount = n)
member _.AsyncAcquire (?timeout) =
async {
let! ok = Async.AwaitWaitHandle (semaphore, ?millisecondsTimeout = timeout)
if ok then
return
{ new IDisposable with
member _.Dispose () = semaphore.Release () |> ignore }
else
return! failwith "couldn't acquire a semaphore"
}
// Gate the number of active web requests
let webRequestGate = RequestGate 5
// The client of the crawler gives up on a request after five seconds
let crawlClient = new HttpClient (Timeout = TimeSpan.FromSeconds 5.0)
// Fetch the URL, and post the results to the urlCollector.
let collectLinks (url : string) =
async {
// An Async web request with a global gate
let! html =
async {
// Acquire an entry in the webRequestGate. Release
// it when 'holder' goes out of scope
use! holder = webRequestGate.AsyncAcquire ()
// Wait for the response
use! response = crawlClient.GetAsync url |> Async.AwaitTask
// Read the response text
return! response.Content.ReadAsStringAsync () |> Async.AwaitTask
}
// Compute the links, synchronously
let links = getLinks html
// Report, synchronously
printfn "finished reading %s, got %d links" url (List.length links)
// We're done
return links
}
/// 'urlCollector' is a single agent that receives URLs as messages. It creates new
/// asynchronous tasks that post messages back to this object.
let urlCollector =
MailboxProcessor.Start (fun self ->
// This is the main state of the urlCollector
let rec waitForUrl (visited : Set<string>) =
async {
// Check the limit
if visited.Count < maxPages then
// Wait for a URL...
let! url = self.Receive ()
if not (visited.Contains url) then
// Start off a new task for the new url. Each collects
// links and posts them back to the urlCollector.
do! Async.StartChild
(async {
let! links = collectLinks url
for link in links do
self.Post link
})
|> Async.Ignore
// Recurse into the waiting state
return! waitForUrl (visited.Add url)
}
// This is the initial state.
waitForUrl Set.empty)
The set of visited addresses is the state of the agent. No lock is
needed: only the agent's own loop reads and changes it.
The session starts from the course's own site. After fifty lines
nothing more is printed. The links found later stay in the mailbox,
unread.
> urlCollector.Post "https://fsharp.pages.taltech.ee";;
finished reading https://fsharp.pages.taltech.ee, got 7 links
finished reading https://fsharp.pages.taltech.ee/, got 7 links
finished reading https://fonts.gstatic.com, got 0 links
finished reading https://gitlab.cs.taltech.ee/fsharp/fsharp.pages.taltech.ee, got 2 links
finished reading https://squidfunk.github.io/mkdocs-material/, got 0 links
finished reading https://about.gitlab.com, got 35 links
finished reading https://about.gitlab.com/de-de/, got 35 links
finished reading https://cdn.cookielaw.org, got 0 links
...
|
16 · Parallel processing
An array initialised in parallel
Async.Parallel can also put all processors to work on one job. Each
of the computations below takes the next free index and fills in that
element, until none is left. Interlocked.Increment adds one to the
shared counter as a single step, so no two computations get the same
index.
// Initialize an array by a parallel init using all available processors
// Note, this primitive doesn't support cancellation.
let parallelArrayInit n f =
let currentLine = ref -1
let res = Array.zeroCreate n
let rec loop () =
let y = Interlocked.Increment (¤tLine.contents)
if y < n then
res[y] <- f y
loop ()
// Start just the right number of tasks, one for each physical CPU
Async.Parallel [ for _ in 1 .. Environment.ProcessorCount -> async { do loop () } ]
|> Async.Ignore
|> Async.RunSynchronously
res
let rec fib x = if x < 2 then 1 else fib (x - 1) + fib (x - 2)
let fibArray = parallelArrayInit 25 (fun x -> fib x)
[|1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; 610; 987; 1597; 2584;
4181; 6765; 10946; 17711; 28657; 46368; 75025|]
|
Threads
Underneath all of this are threads. A thread can be created and
started directly:
let t =
Thread (ThreadStart (fun _ ->
printfn "Thread %d: Hello" Thread.CurrentThread.ManagedThreadId))
t.Join () waits until the thread has finished. Send the four lines
as one input:
> t.Start ()
printfn "Thread %d: Waiting!" Thread.CurrentThread.ManagedThreadId
t.Join ()
printfn "Done!";;
Thread 33: HelloThread
2: Waiting!
Done!
|
Thread 33 is the new thread and thread 2 the one that runs our input.
They printed at the same moment, and the pieces of their two lines got
mixed. In another run the lines come out whole, in either order.
Tasks and cancellation
A .NET task is started with Task.Run. A task can be cancelled, if it
cooperates: it is handed a cancellation token and checks it from time
to time.
open System.Threading.Tasks
let doSome1Thing () =
printfn "doing some 1 thing ..."
Thread.Sleep 100
printfn "... done some 1 thing."
let doSome2Thing (_ : CancellationToken) =
printfn "doing some 2 thing ..."
Thread.Sleep 100
printfn "... done some 2 thing."
let doSome3Thing (ct : CancellationToken) =
printfn "doing some 3 thing ..."
ct.ThrowIfCancellationRequested ()
Thread.Sleep 100
ct.ThrowIfCancellationRequested ()
printfn "... done some 3 thing."
let cts = new CancellationTokenSource ()
The first task has nothing to do with the token. The second receives
it and ignores it. The third checks it before and after its work. Send
the five lines as one input, so that the token is cancelled while the
tasks are running. The short sleep gives the tasks time to start:
> let task1 = Task.Run (fun () -> doSome1Thing ())
let task2 = Task.Run ((fun () -> doSome2Thing cts.Token), cts.Token)
let task3 = Task.Run ((fun () -> doSome3Thing cts.Token), cts.Token)
Thread.Sleep 50
cts.Cancel ();;
doing some 1 thing ...
doing some 2 thing ...
doing some 3 thing ...
val task1: Task
val task2: Task
val task3: Task
... done some 1 thing.
... done some 2 thing.
> task1.Status, task2.Status, task3.Status;;
val it: TaskStatus * TaskStatus * TaskStatus =
(RanToCompletion, RanToCompletion, Canceled)
|
The first two tasks finish their work. The third notices the
cancellation at its second check and ends as Canceled, without
printing its last line.
The token is also the second argument of Task.Run. A task whose token
is already cancelled when it would start does not run at all:
> let task4 = Task.Run ((fun () -> doSome2Thing cts.Token), cts.Token);;
val task4: Task
> task4.Status;;
val it: TaskStatus = Canceled
|
Without the sleep, the second and the third task above can end the
same way: cancelled before they have printed anything.
(The 2025 version of this script wrote
Task.Run (fun () -> doSome2Thing (cts.Token), cts.Token). That passes
no token to Task.Run: the function returns a pair, and the result is
a Task<unit * CancellationToken>.)
Summary
-
An event is a value: callbacks are added to it, and events are
filtered, mapped and merged like collections.
- A sequence is pulled; an observable pushes.
-
async { } describes a computation that can wait without holding a
thread; it runs when it is started.
-
Async.Parallel combines computations and keeps the order of its
inputs.
-
An agent keeps its state inside a message loop; state shared between
threads needs a lock.
Homework, reading and next week
Homework 9 is out this week.
Reading:
The examples of events, agents, image processing and the web crawler
are based on Expert F# 4.0 by Don Syme, Adam Granicz and Antonio
Cisternino.
Next week: type providers and dynamic code generation.
namespace System
namespace System.IO
val watchDir: string
type Path =
static member ChangeExtension: path: string * extension: string -> string
static member Combine: path1: string * path2: string -> string + 4 overloads
static member EndsInDirectorySeparator: path: ReadOnlySpan<char> -> bool + 1 overload
static member Exists: path: string -> bool
static member GetDirectoryName: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetExtension: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetFileName: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetFileNameWithoutExtension: path: ReadOnlySpan<char> -> ReadOnlySpan<char> + 1 overload
static member GetFullPath: path: string -> string + 1 overload
static member GetInvalidFileNameChars: unit -> char array
...
<summary>Performs operations on <see cref="T:System.String" /> instances that contain file or directory path information. These operations are performed in a cross-platform manner.</summary>
Path.Combine(paths: ReadOnlySpan<string>) : string
Path.Combine( paths: string array) : string
Path.Combine(path1: string, path2: string) : string
Path.Combine(path1: string, path2: string, path3: string) : string
Path.Combine(path1: string, path2: string, path3: string, path4: string) : string
Path.GetTempPath() : string
type Directory =
static member CreateDirectory: path: string -> DirectoryInfo + 1 overload
static member CreateSymbolicLink: path: string * pathToTarget: string -> FileSystemInfo
static member CreateTempSubdirectory: ?prefix: string -> DirectoryInfo
static member Delete: path: string -> unit + 1 overload
static member EnumerateDirectories: path: string -> string seq + 3 overloads
static member EnumerateFileSystemEntries: path: string -> string seq + 3 overloads
static member EnumerateFiles: path: string -> string seq + 3 overloads
static member Exists: path: string -> bool
static member GetCreationTime: path: string -> DateTime
static member GetCreationTimeUtc: path: string -> DateTime
...
<summary>Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.</summary>
Directory.CreateDirectory(path: string) : DirectoryInfo
Directory.CreateDirectory(path: string, unixCreateMode: UnixFileMode) : DirectoryInfo
val ignore: value: 'T -> unit
val watcher: FileSystemWatcher
Multiple items
type FileSystemWatcher =
inherit Component
interface ISupportInitialize
new: unit -> unit + 2 overloads
member BeginInit: unit -> unit
member EndInit: unit -> unit
member WaitForChanged: changeType: WatcherChangeTypes -> WaitForChangedResult + 2 overloads
member EnableRaisingEvents: bool
member Filter: string
member Filters: Collection<string>
member IncludeSubdirectories: bool
...
<summary>Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.</summary>
--------------------
FileSystemWatcher() : FileSystemWatcher
FileSystemWatcher(path: string) : FileSystemWatcher
FileSystemWatcher(path: string, filter: string) : FileSystemWatcher
event FileSystemWatcher.Changed: IEvent<FileSystemEventHandler,FileSystemEventArgs>
member IObservable.Add: callback: ('T -> unit) -> unit
val args: FileSystemEventArgs
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
property FileSystemEventArgs.Name: string with get
<summary>Gets the name of the affected file or directory.</summary>
<returns>The name of the affected file or directory.</returns>
val handler: FileSystemEventHandler
type FileSystemEventHandler =
new: object: obj * method: nativeint -> unit
member BeginInvoke: sender: obj * e: FileSystemEventArgs * callback: AsyncCallback * object: obj -> IAsyncResult
member EndInvoke: result: IAsyncResult -> unit
member Invoke: sender: obj * e: FileSystemEventArgs -> unit
<summary>Represents the method that will handle the <see cref="E:System.IO.FileSystemWatcher.Changed" />, <see cref="E:System.IO.FileSystemWatcher.Created" />, or <see cref="E:System.IO.FileSystemWatcher.Deleted" /> event of a <see cref="T:System.IO.FileSystemWatcher" /> class.</summary>
<param name="sender">The source of the event.</param>
<param name="e">The <see cref="T:System.IO.FileSystemEventArgs" /> that contains the event data.</param>
event FileSystemWatcher.Created: IEvent<FileSystemEventHandler,FileSystemEventArgs>
abstract IDelegateEvent.AddHandler: handler: 'Delegate -> unit
abstract IDelegateEvent.RemoveHandler: handler: 'Delegate -> unit
val manual: Event<int>
Multiple items
module Event
from Microsoft.FSharp.Control
--------------------
type Event<'T> =
new: unit -> Event<'T>
member Trigger: arg: 'T -> unit
member Publish: IEvent<'T>
--------------------
type Event<'Delegate,'Args (requires delegate and 'Delegate :> Delegate and reference type and 'Delegate: not null)> =
new: unit -> Event<'Delegate,'Args>
member Trigger: sender: objnull * args: 'Args -> unit
member Publish: IEvent<'Delegate,'Args>
--------------------
new: unit -> Event<'T>
--------------------
new: unit -> Event<'Delegate,'Args>
Multiple items
val int: value: 'T -> int (requires member op_Explicit)
--------------------
type int = int32
--------------------
type int<'Measure> =
int
property Event.Publish: IEvent<int> with get
val n: int
member Event.Trigger: arg: 'T -> unit
Multiple items
type RandomTicker =
interface IDisposable
new: approxInterval: int -> RandomTicker
member Start: unit -> unit
member Stop: unit -> unit
member RandomTick: IEvent<int>
--------------------
new: approxInterval: int -> RandomTicker
val approxInterval: int
val timer: Timers.Timer
namespace System.Timers
Multiple items
type Timer =
inherit Component
interface ISupportInitialize
new: unit -> unit + 2 overloads
member BeginInit: unit -> unit
member Close: unit -> unit
member EndInit: unit -> unit
member Start: unit -> unit
member Stop: unit -> unit
member AutoReset: bool
member Enabled: bool
...
<summary>Generates an event after a set interval, with an option to generate recurring events.</summary>
--------------------
Timers.Timer() : Timers.Timer
Timers.Timer(interval: float) : Timers.Timer
Timers.Timer(interval: TimeSpan) : Timers.Timer
val rnd: Random
Multiple items
type Random =
new: unit -> unit + 1 overload
member GetHexString: stringLength: int * ?lowercase: bool -> string + 1 overload
member GetItems<'T> : choices: ReadOnlySpan<'T> * length: int -> 'T array + 2 overloads
member GetString: choices: ReadOnlySpan<char> * length: int -> string
member Next: unit -> int + 2 overloads
member NextBytes: buffer: byte array -> unit + 1 overload
member NextDouble: unit -> float
member NextInt64: unit -> int64 + 2 overloads
member NextSingle: unit -> float32
member Shuffle<'T> : values: Span<'T> -> unit + 1 overload
...
<summary>Represents a pseudo-random number generator, which is an algorithm that produces a sequence of numbers that meet certain statistical requirements for randomness.</summary>
--------------------
Random() : Random
Random(Seed: int) : Random
val tickEvent: Event<int>
val chooseInterval: unit -> int
Random.Next() : int
Random.Next(maxValue: int) : int
Random.Next(minValue: int, maxValue: int) : int
property Timers.Timer.Interval: float with get, set
<summary>Gets or sets the interval, expressed in milliseconds, at which to raise the <see cref="E:System.Timers.Timer.Elapsed" /> event.</summary>
<exception cref="T:System.ArgumentException">The interval is less than or equal to zero.
-or-
The interval is greater than <see cref="F:System.Int32.MaxValue">Int32.MaxValue</see>, and the timer is currently enabled. (If the timer is not currently enabled, no exception is thrown until it becomes enabled.)</exception>
<returns>The time, in milliseconds, between <see cref="E:System.Timers.Timer.Elapsed" /> events. The value must be greater than zero, and less than or equal to <see cref="F:System.Int32.MaxValue">Int32.MaxValue</see>. The default is 100 milliseconds.</returns>
event Timers.Timer.Elapsed: IEvent<Timers.ElapsedEventHandler,Timers.ElapsedEventArgs>
<summary>Occurs when the interval elapses.</summary>
val interval: int
Timers.Timer.Start() : unit
Timers.Timer.Stop() : unit
type IDisposable =
override Dispose: unit -> unit
<summary>Provides a mechanism for releasing unmanaged resources.</summary>
ComponentModel.Component.Dispose() : unit
val rt: RandomTicker
property RandomTicker.RandomTick: IEvent<int> with get
val nextInterval: int
val filter: predicate: ('T -> bool) -> sourceEvent: IEvent<'Del,'T> -> IEvent<'T> (requires delegate and 'Del :> Delegate and 'Del: not null)
val add: callback: ('T -> unit) -> sourceEvent: IEvent<'Del,'T> -> unit (requires delegate and 'Del :> Delegate and 'Del: not null)
val ticks: Event<int>
val words: Event<string>
Multiple items
val string: value: 'T -> string
--------------------
type string = String
val evens: IObservable<int>
module Observable
from Microsoft.FSharp.Control
val filter: predicate: ('T -> bool) -> source: IObservable<'T> -> IObservable<'T>
val i: int
val evs: IObservable<int>
val odds: IObservable<int>
val partition: predicate: ('T -> bool) -> source: IObservable<'T> -> IObservable<'T> * IObservable<'T>
val soEven: IObservable<string>
val map: mapping: ('T -> 'U) -> source: IObservable<'T> -> IObservable<'U>
val sprintf: format: Printf.StringFormat<'T> -> 'T
val strCount: IObservable<int>
property Event.Publish: IEvent<string> with get
val scan: collector: ('U -> 'T -> 'U) -> state: 'U -> source: IObservable<'T> -> IObservable<'U>
val acc: int
val merged: IObservable<int>
val merge: source1: IObservable<'T> -> source2: IObservable<'T> -> IObservable<'T>
val obsStr: IDisposable
val subscribe: callback: ('T -> unit) -> source: IObservable<'T> -> IDisposable
val s: string
val obs1: IDisposable
val obs2: IDisposable
val w: string
IDisposable.Dispose() : unit
Multiple items
type StringTicker =
interface IDisposable
new: approxInterval: int -> StringTicker
member Start: unit -> unit
member Stop: unit -> unit
member RandomTick: IEvent<string>
--------------------
new: approxInterval: int -> StringTicker
val tickEvent: Event<string>
val rt2: RandomTicker
val st: StringTicker
property StringTicker.RandomTick: IEvent<string> with get
namespace System.Net
namespace System.Net.Http
val downloadSync: url: string -> string
val url: string
val client: HttpClient
Multiple items
type HttpClient =
inherit HttpMessageInvoker
new: unit -> unit + 2 overloads
member CancelPendingRequests: unit -> unit
member DeleteAsync: requestUri: string -> Task<HttpResponseMessage> + 3 overloads
member GetAsync: requestUri: string -> Task<HttpResponseMessage> + 7 overloads
member GetByteArrayAsync: requestUri: string -> Task<byte array> + 3 overloads
member GetStreamAsync: requestUri: string -> Task<Stream> + 3 overloads
member GetStringAsync: requestUri: string -> Task<string> + 3 overloads
member PatchAsync: requestUri: string * content: HttpContent -> Task<HttpResponseMessage> + 3 overloads
member PostAsync: requestUri: string * content: HttpContent -> Task<HttpResponseMessage> + 3 overloads
...
<summary>Provides a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.</summary>
--------------------
HttpClient() : HttpClient
HttpClient(handler: HttpMessageHandler) : HttpClient
HttpClient(handler: HttpMessageHandler, disposeHandler: bool) : HttpClient
val request: HttpRequestMessage
Multiple items
type HttpRequestMessage =
interface IDisposable
new: unit -> unit + 2 overloads
member Dispose: unit -> unit
member ToString: unit -> string
member Content: HttpContent
member Headers: HttpRequestHeaders
member Method: HttpMethod
member Options: HttpRequestOptions
member Properties: IDictionary<string,obj>
member RequestUri: Uri
...
<summary>Represents a HTTP request message.</summary>
--------------------
HttpRequestMessage() : HttpRequestMessage
HttpRequestMessage(method: HttpMethod, requestUri: string) : HttpRequestMessage
HttpRequestMessage(method: HttpMethod, requestUri: Uri) : HttpRequestMessage
Multiple items
type HttpMethod =
interface IEquatable<HttpMethod>
new: method: string -> unit
member Equals: other: HttpMethod -> bool + 1 overload
member GetHashCode: unit -> int
member ToString: unit -> string
static member (<>) : left: HttpMethod * right: HttpMethod -> bool
static member (=) : left: HttpMethod * right: HttpMethod -> bool
static member Parse: method: ReadOnlySpan<char> -> HttpMethod
member Method: string
static member Connect: HttpMethod
...
<summary>A helper class for retrieving and comparing standard HTTP methods and for creating new HTTP methods.</summary>
--------------------
HttpMethod(method: string) : HttpMethod
property HttpMethod.Get: HttpMethod with get
<summary>Represents an HTTP GET protocol method.</summary>
<returns>The HTTP GET method.</returns>
val response: HttpResponseMessage
HttpClient.Send(request: HttpRequestMessage) : HttpResponseMessage
HttpClient.Send(request: HttpRequestMessage, cancellationToken: Threading.CancellationToken) : HttpResponseMessage
HttpClient.Send(request: HttpRequestMessage, completionOption: HttpCompletionOption) : HttpResponseMessage
HttpClient.Send(request: HttpRequestMessage, completionOption: HttpCompletionOption, cancellationToken: Threading.CancellationToken) : HttpResponseMessage
val stream: Stream
property HttpResponseMessage.Content: HttpContent with get, set
<summary>Gets or sets the content of a HTTP response message.</summary>
<returns>The content of the HTTP response message.</returns>
HttpContent.ReadAsStream() : Stream
HttpContent.ReadAsStream(cancellationToken: Threading.CancellationToken) : Stream
val reader: StreamReader
Multiple items
type StreamReader =
inherit TextReader
new: stream: Stream -> unit + 12 overloads
member Close: unit -> unit
member DiscardBufferedData: unit -> unit
member Peek: unit -> int
member Read: unit -> int + 2 overloads
member ReadAsync: buffer: char array * index: int * count: int -> Task<int> + 1 overload
member ReadBlock: buffer: char array * index: int * count: int -> int + 1 overload
member ReadBlockAsync: buffer: char array * index: int * count: int -> Task<int> + 1 overload
member ReadLine: unit -> string
...
<summary>Implements a <see cref="T:System.IO.TextReader" /> that reads characters from a byte stream in a particular encoding.</summary>
--------------------
StreamReader(stream: Stream) : StreamReader
(+0 other overloads)
StreamReader(path: string) : StreamReader
(+0 other overloads)
StreamReader(stream: Stream, detectEncodingFromByteOrderMarks: bool) : StreamReader
(+0 other overloads)
StreamReader(stream: Stream, encoding: Text.Encoding) : StreamReader
(+0 other overloads)
StreamReader(path: string, detectEncodingFromByteOrderMarks: bool) : StreamReader
(+0 other overloads)
StreamReader(path: string, options: FileStreamOptions) : StreamReader
(+0 other overloads)
StreamReader(path: string, encoding: Text.Encoding) : StreamReader
(+0 other overloads)
StreamReader(stream: Stream, encoding: Text.Encoding, detectEncodingFromByteOrderMarks: bool) : StreamReader
(+0 other overloads)
StreamReader(path: string, encoding: Text.Encoding, detectEncodingFromByteOrderMarks: bool) : StreamReader
(+0 other overloads)
StreamReader(stream: Stream, encoding: Text.Encoding, detectEncodingFromByteOrderMarks: bool, bufferSize: int) : StreamReader
(+0 other overloads)
StreamReader.ReadToEnd() : string
val readToEndAsync: reader: StreamReader -> Async<string>
Multiple items
type Async =
static member AsBeginEnd: computation: ('Arg -> Async<'T>) -> ('Arg * AsyncCallback * objnull -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent: event: IEvent<'Del,'T> * ?cancelAction: (unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate and 'Del: not null)
static member AwaitIAsyncResult: iar: IAsyncResult * ?millisecondsTimeout: int -> Async<bool>
static member AwaitTask: task: Task<'T> -> Async<'T> + 1 overload
static member AwaitWaitHandle: waitHandle: WaitHandle * ?millisecondsTimeout: int -> Async<bool>
static member CancelDefaultToken: unit -> unit
static member Catch: computation: Async<'T> -> Async<Choice<'T,exn>>
static member Choice: computations: Async<'T option> seq -> Async<'T option>
static member FromBeginEnd: beginAction: (AsyncCallback * objnull -> IAsyncResult) * endAction: (IAsyncResult -> 'T) * ?cancelAction: (unit -> unit) -> Async<'T> + 3 overloads
static member FromContinuations: callback: (('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
...
--------------------
type Async<'T>
static member Async.AwaitTask: task: Threading.Tasks.Task -> Async<unit>
static member Async.AwaitTask: task: Threading.Tasks.Task<'T> -> Async<'T>
StreamReader.ReadToEndAsync() : Threading.Tasks.Task<string>
StreamReader.ReadToEndAsync(cancellationToken: Threading.CancellationToken) : Threading.Tasks.Task<string>
val downloadAsync: url: string -> Async<string>
val async: AsyncBuilder
HttpClient.GetAsync(requestUri: Uri) : Threading.Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string) : Threading.Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync(requestUri: Uri, cancellationToken: Threading.CancellationToken) : Threading.Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync(requestUri: Uri, completionOption: HttpCompletionOption) : Threading.Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string, cancellationToken: Threading.CancellationToken) : Threading.Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string, completionOption: HttpCompletionOption) : Threading.Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync(requestUri: Uri, completionOption: HttpCompletionOption, cancellationToken: Threading.CancellationToken) : Threading.Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string, completionOption: HttpCompletionOption, cancellationToken: Threading.CancellationToken) : Threading.Tasks.Task<HttpResponseMessage>
HttpResponseMessage.EnsureSuccessStatusCode() : HttpResponseMessage
val content: string
HttpContent.ReadAsStringAsync() : Threading.Tasks.Task<string>
HttpContent.ReadAsStringAsync(cancellationToken: Threading.CancellationToken) : Threading.Tasks.Task<string>
val result: Async<string>
val downloadAsyncVerbose: url: string -> Async<string>
val threadId: int
namespace System.Threading
Multiple items
type Thread =
inherit CriticalFinalizerObject
new: start: ParameterizedThreadStart -> unit + 3 overloads
member Abort: unit -> unit + 1 overload
member DisableComObjectEagerCleanup: unit -> unit
member GetApartmentState: unit -> ApartmentState
member GetCompressedStack: unit -> CompressedStack
member GetHashCode: unit -> int
member Interrupt: unit -> unit
member Join: unit -> unit + 2 overloads
member Resume: unit -> unit
...
<summary>Creates and controls a thread, sets its priority, and gets its status.</summary>
--------------------
Threading.Thread(start: Threading.ParameterizedThreadStart) : Threading.Thread
Threading.Thread(start: Threading.ThreadStart) : Threading.Thread
Threading.Thread(start: Threading.ParameterizedThreadStart, maxStackSize: int) : Threading.Thread
Threading.Thread(start: Threading.ThreadStart, maxStackSize: int) : Threading.Thread
property Threading.Thread.CurrentThread: Threading.Thread with get
<summary>Gets the currently running thread.</summary>
<returns>A <see cref="T:System.Threading.Thread" /> that is the representation of the currently running thread.</returns>
property Threading.Thread.ManagedThreadId: int with get
<summary>Gets a unique identifier for the current managed thread.</summary>
<returns>An integer that represents a unique identifier for this managed thread.</returns>
val aresult: Async<string>
val getHttp: client: HttpClient -> url: string -> Threading.Tasks.Task<string>
val task: TaskBuilder
val museums: (string * string) list
val downloads: Async<string array>
static member Async.Parallel: computations: Async<'T> seq -> Async<'T array>
static member Async.Parallel: computations: Async<'T> seq * ?maxDegreeOfParallelism: int -> Async<'T array>
val sleepAsync: time: float -> Async<unit>
val time: float
Multiple items
val float: value: 'T -> float (requires member op_Explicit)
--------------------
type float = Double
--------------------
type float<'Measure> =
float
static member Async.FromContinuations: callback: (('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
val successCont: (unit -> unit)
val exnCont: (exn -> unit)
val cancelCont: (OperationCanceledException -> unit)
event Timers.Timer.Elapsed: IEvent<Timers.ElapsedEventHandler,Timers.ElapsedEventArgs>
val timerTest: Async<unit>
static member Async.RunSynchronously: computation: Async<'T> * ?timeout: int * ?cancellationToken: Threading.CancellationToken -> 'T
val kumu: Async<string>
val html: string
val kumu': Async<string>
member AsyncBuilder.Delay: generator: (unit -> Async<'T>) -> Async<'T>
member AsyncBuilder.Bind: computation: Async<'T> * binder: ('T -> Async<'U>) -> Async<'U>
member AsyncBuilder.Return: value: 'T -> Async<'T>
val squares: int array
val failingAsync: Async<unit>
val failwith: message: string -> 'T
val failingAsyncs: Async<unit> list
val caught: string
static member Async.Catch: computation: Async<'T> -> Async<Choice<'T,exn>>
union case Choice.Choice1Of2: 'T1 -> Choice<'T1,'T2>
union case Choice.Choice2Of2: 'T2 -> Choice<'T1,'T2>
val e: exn
property Exception.Message: string with get
type Agent<'T> = MailboxProcessor<'T>
'T
Multiple items
type MailboxProcessor<'Msg> =
interface IDisposable
new: body: (MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken: CancellationToken -> MailboxProcessor<'Msg> + 1 overload
member Dispose: unit -> unit
member Post: message: 'Msg -> unit
member PostAndAsyncReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> Async<'Reply>
member PostAndReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> 'Reply
member PostAndTryAsyncReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> Async<'Reply option>
member Receive: ?timeout: int -> Async<'Msg>
member Scan: scanner: ('Msg -> Async<'T> option) * ?timeout: int -> Async<'T>
member TryPostAndReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> 'Reply option
...
--------------------
new: body: (MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken: Threading.CancellationToken -> MailboxProcessor<'Msg>
new: body: (MailboxProcessor<'Msg> -> Async<unit>) * isThrowExceptionAfterDisposed: bool * ?cancellationToken: Threading.CancellationToken -> MailboxProcessor<'Msg>
val counter: Agent<int>
val inbox: MailboxProcessor<int>
val loop: n: int -> Async<'a>
val msg: int
member MailboxProcessor.Receive: ?timeout: int -> Async<'Msg>
val accept: Agent<int>
val accept: unit -> Async<'a>
val reject: unit -> Async<'a>
type CounterMessage =
| Increment of int
| Fetch of AsyncReplyChannel<int>
| Stop
The type of messages for the agent
type AsyncReplyChannel<'Reply> =
member Reply: value: 'Reply -> unit
Multiple items
type CountingAgent =
new: unit -> CountingAgent
member Fetch: unit -> int
member Increment: n: int -> unit
member Stop: unit -> unit
--------------------
new: unit -> CountingAgent
val counter: MailboxProcessor<CounterMessage>
static member MailboxProcessor.Start: body: (MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken: Threading.CancellationToken -> MailboxProcessor<'Msg>
static member MailboxProcessor.Start: body: (MailboxProcessor<'Msg> -> Async<unit>) * isThrowExceptionAfterDisposed: bool * ?cancellationToken: Threading.CancellationToken -> MailboxProcessor<'Msg>
val inbox: MailboxProcessor<CounterMessage>
val loop: n: int -> Async<unit>
val msg: CounterMessage
union case CounterMessage.Increment: int -> CounterMessage
val m: int
union case CounterMessage.Stop: CounterMessage
union case CounterMessage.Fetch: AsyncReplyChannel<int> -> CounterMessage
val replyChannel: AsyncReplyChannel<int>
member AsyncReplyChannel.Reply: value: 'Reply -> unit
member MailboxProcessor.Post: message: 'Msg -> unit
member MailboxProcessor.PostAndReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> 'Reply
val counting: CountingAgent
member CountingAgent.Increment: n: int -> unit
val fetched1: int
member CountingAgent.Fetch: unit -> int
val fetched2: int
member CountingAgent.Stop: unit -> unit
type Message =
| Message1
| Message2 of int
| Message3 of string
val agent: MailboxProcessor<Message>
val inbox: MailboxProcessor<Message>
val loop: unit -> Async<'a>
member MailboxProcessor.Scan: scanner: ('Msg -> Async<'T> option) * ?timeout: int -> Async<'T>
union case Message.Message1: Message
union case Option.Some: Value: 'T -> Option<'T>
union case Message.Message2: int -> Message
union case Message.Message3: string -> Message
union case Option.None: Option<'T>
Multiple items
type MutablePair<'T,'U> =
new: x: 'T * y: 'U -> MutablePair<'T,'U>
member Update: x: 'T * y: 'U -> unit
member Value: 'T * 'U
--------------------
new: x: 'T * y: 'U -> MutablePair<'T,'U>
'U
val x: 'T
val y: 'U
val mutable currentX: 'T
val mutable currentY: 'U
val p: MutablePair<int,int>
val lock: lockobj: obj -> f: (unit -> 'a) -> 'a
val lockobj: obj
type obj = Object
val f: (unit -> 'a)
type Monitor =
static member Enter: obj: obj -> unit + 1 overload
static member Exit: obj: obj -> unit
static member IsEntered: obj: obj -> bool
static member Pulse: obj: obj -> unit
static member PulseAll: obj: obj -> unit
static member TryEnter: obj: obj -> bool + 5 overloads
static member Wait: obj: obj -> bool + 4 overloads
static member LockContentionCount: int64
<summary>Provides a mechanism that synchronizes access to objects.</summary>
Monitor.Enter(obj: obj) : unit
Monitor.Enter(obj: obj, lockTaken: byref<bool>) : unit
Monitor.Exit(obj: obj) : unit
val readLock: rwlock: ReaderWriterLock -> f: (unit -> 'a) -> 'a
val rwlock: ReaderWriterLock
Multiple items
type ReaderWriterLock =
inherit CriticalFinalizerObject
new: unit -> unit
member AcquireReaderLock: millisecondsTimeout: int -> unit + 1 overload
member AcquireWriterLock: millisecondsTimeout: int -> unit + 1 overload
member AnyWritersSince: seqNum: int -> bool
member DowngradeFromWriterLock: lockCookie: byref<LockCookie> -> unit
member ReleaseLock: unit -> LockCookie
member ReleaseReaderLock: unit -> unit
member ReleaseWriterLock: unit -> unit
member RestoreLock: lockCookie: byref<LockCookie> -> unit
...
<summary>Defines a lock that supports single writers and multiple readers.</summary>
--------------------
ReaderWriterLock() : ReaderWriterLock
ReaderWriterLock.AcquireReaderLock(timeout: TimeSpan) : unit
ReaderWriterLock.AcquireReaderLock(millisecondsTimeout: int) : unit
type Timeout =
static val Infinite: int
static val InfiniteTimeSpan: TimeSpan
<summary>Contains constants that specify infinite time-out intervals. This class cannot be inherited.</summary>
field Timeout.Infinite: int = -1
ReaderWriterLock.ReleaseReaderLock() : unit
val writeLock: rwlock: ReaderWriterLock -> f: (unit -> unit) -> unit
val f: (unit -> unit)
ReaderWriterLock.AcquireWriterLock(timeout: TimeSpan) : unit
ReaderWriterLock.AcquireWriterLock(millisecondsTimeout: int) : unit
Multiple items
type Thread =
inherit CriticalFinalizerObject
new: start: ParameterizedThreadStart -> unit + 3 overloads
member Abort: unit -> unit + 1 overload
member DisableComObjectEagerCleanup: unit -> unit
member GetApartmentState: unit -> ApartmentState
member GetCompressedStack: unit -> CompressedStack
member GetHashCode: unit -> int
member Interrupt: unit -> unit
member Join: unit -> unit + 2 overloads
member Resume: unit -> unit
...
<summary>Creates and controls a thread, sets its priority, and gets its status.</summary>
--------------------
Thread(start: ParameterizedThreadStart) : Thread
Thread(start: ThreadStart) : Thread
Thread(start: ParameterizedThreadStart, maxStackSize: int) : Thread
Thread(start: ThreadStart, maxStackSize: int) : Thread
Thread.MemoryBarrier() : unit
ReaderWriterLock.ReleaseWriterLock() : unit
Multiple items
type LockedPair<'T,'U> =
new: x: 'T * y: 'U -> LockedPair<'T,'U>
member Update: x: 'T * y: 'U -> unit
member Value: 'T * 'U
--------------------
new: x: 'T * y: 'U -> LockedPair<'T,'U>
val lp: LockedPair<int,int>
member LockedPair.Update: x: 'T * y: 'U -> unit
val lpValue: int * int
property LockedPair.Value: int * int with get
val fibs: n: int -> int
namespace System.Collections
namespace System.Collections.Generic
val memoize: f: ('a -> 'b) -> ('a -> 'b) (requires equality)
The function creates a function that calls the argument 'f'
only once and stores the result in a mutable dictionary (cache)
Repeated calls to the resulting function return cached values.
val f: ('a -> 'b) (requires equality)
val cache: Dictionary<'a,'b> (requires equality)
Multiple items
type Dictionary<'TKey,'TValue> =
interface ICollection<KeyValuePair<'TKey,'TValue>>
interface seq<KeyValuePair<'TKey,'TValue>>
interface IEnumerable
interface IDictionary<'TKey,'TValue>
interface IReadOnlyCollection<KeyValuePair<'TKey,'TValue>>
interface IReadOnlyDictionary<'TKey,'TValue>
interface ICollection
interface IDictionary
interface IDeserializationCallback
interface ISerializable
...
<summary>Represents a collection of keys and values.</summary>
<typeparam name="TKey">The type of the keys in the dictionary.</typeparam>
<typeparam name="TValue">The type of the values in the dictionary.</typeparam>
--------------------
Dictionary() : Dictionary<'TKey,'TValue>
Dictionary(dictionary: IDictionary<'TKey,'TValue>) : Dictionary<'TKey,'TValue>
Dictionary(collection: KeyValuePair<'TKey,'TValue> seq) : Dictionary<'TKey,'TValue>
Dictionary(comparer: IEqualityComparer<'TKey>) : Dictionary<'TKey,'TValue>
Dictionary(capacity: int) : Dictionary<'TKey,'TValue>
Dictionary(dictionary: IDictionary<'TKey,'TValue>, comparer: IEqualityComparer<'TKey>) : Dictionary<'TKey,'TValue>
Dictionary(collection: KeyValuePair<'TKey,'TValue> seq, comparer: IEqualityComparer<'TKey>) : Dictionary<'TKey,'TValue>
Dictionary(capacity: int, comparer: IEqualityComparer<'TKey>) : Dictionary<'TKey,'TValue>
val x: 'a (requires equality)
val succ: bool
val v: 'b
Dictionary.TryGetValue(key: 'a, value: byref<'b>) : bool
Dictionary.Add(key: 'a, value: 'b) : unit
val memfibs: (int -> int)
val fibsm: (int -> int)
val fibsm44: int
val numImages: int
val size: int
val numPixels: int
val imageDir: string
val imageFile: i: int -> extension: string -> string
val extension: string
val makeImageFiles: unit -> unit
val pixels: byte array
type Array =
interface ICollection
interface IEnumerable
interface IList
interface IStructuralComparable
interface IStructuralEquatable
interface ICloneable
member Clone: unit -> obj
member CopyTo: array: Array * index: int -> unit + 1 overload
member GetEnumerator: unit -> IEnumerator
member GetLength: dimension: int -> int
...
<summary>Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.</summary>
val init: count: int -> initializer: (int -> 'T) -> 'T array
Multiple items
val byte: value: 'T -> byte (requires member op_Explicit)
--------------------
type byte = Byte
--------------------
type byte<'Measure> =
byte
type File =
static member AppendAllBytes: path: string * bytes: byte array -> unit + 1 overload
static member AppendAllBytesAsync: path: string * bytes: byte array * ?cancellationToken: CancellationToken -> Task + 1 overload
static member AppendAllLines: path: string * contents: string seq -> unit + 1 overload
static member AppendAllLinesAsync: path: string * contents: string seq * encoding: Encoding * ?cancellationToken: CancellationToken -> Task + 1 overload
static member AppendAllText: path: string * contents: ReadOnlySpan<char> -> unit + 3 overloads
static member AppendAllTextAsync: path: string * contents: ReadOnlyMemory<char> * encoding: Encoding * ?cancellationToken: CancellationToken -> Task + 3 overloads
static member AppendText: path: string -> StreamWriter
static member Copy: sourceFileName: string * destFileName: string -> unit + 1 overload
static member Create: path: string -> FileStream + 2 overloads
static member CreateSymbolicLink: path: string * pathToTarget: string -> FileSystemInfo
...
<summary>Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of <see cref="T:System.IO.FileStream" /> objects.</summary>
File.WriteAllBytes(path: string, bytes: ReadOnlySpan<byte>) : unit
File.WriteAllBytes(path: string, bytes: byte array) : unit
val processImageRepeats: int
val transformImage: pixels: byte array * imageNum: int -> byte array
val imageNum: int
val i: int32
val map: mapping: ('T -> 'U) -> array: 'T array -> 'U array
val b: byte
val processImageSync: i: int -> unit
val inStream: FileStream
File.OpenRead(path: string) : FileStream
val zeroCreate: count: int -> 'T array
val nPixels: int
FileStream.Read(buffer: Span<byte>) : int
FileStream.Read(buffer: byte array, offset: int, count: int) : int
val pixels': byte array
val outStream: FileStream
File.OpenWrite(path: string) : FileStream
FileStream.Write(buffer: ReadOnlySpan<byte>) : unit
FileStream.Write(buffer: byte array, offset: int, count: int) : unit
val processImagesSync: unit -> unit
val processImageAsync: i: int -> Async<unit>
member Stream.AsyncRead: count: int -> Async<byte array>
member Stream.AsyncRead: buffer: byte array * ?offset: int * ?count: int -> Async<int>
member Stream.AsyncWrite: buffer: byte array * ?offset: int * ?count: int -> Async<unit>
val processImagesAsync: unit -> unit
val tasks: Async<unit> list
static member Async.RunSynchronously: computation: Async<'T> * ?timeout: int * ?cancellationToken: CancellationToken -> 'T
val delay: Async<unit>
static member Async.Sleep: dueTime: TimeSpan -> Async<unit>
static member Async.Sleep: millisecondsDueTime: int -> Async<unit>
namespace System.Text
namespace System.Text.RegularExpressions
val maxPages: int
val linkPat: string
val getLinks: txt: string -> string list
val txt: string
val m: Match
Multiple items
type Regex =
interface ISerializable
new: pattern: string -> unit + 2 overloads
member Count: input: string -> int + 8 overloads
member EnumerateMatches: input: ReadOnlySpan<char> -> ValueMatchEnumerator + 4 overloads
member EnumerateSplits: input: ReadOnlySpan<char> -> ValueSplitEnumerator + 5 overloads
member GetGroupNames: unit -> string array
member GetGroupNumbers: unit -> int array
member GroupNameFromNumber: i: int -> string
member GroupNumberFromName: name: string -> int
member IsMatch: input: ReadOnlySpan<char> -> bool + 9 overloads
...
<summary>Represents an immutable regular expression.</summary>
--------------------
Regex( pattern: string) : Regex
Regex( pattern: string, options: RegexOptions) : Regex
Regex( pattern: string, options: RegexOptions, matchTimeout: TimeSpan) : Regex
Regex.Matches(input: string, pattern: string) : MatchCollection
Regex.Matches(input: string, pattern: string, options: RegexOptions) : MatchCollection
Regex.Matches(input: string, pattern: string, options: RegexOptions, matchTimeout: TimeSpan) : MatchCollection
property Match.Groups: GroupCollection with get
<summary>Gets a collection of groups matched by the regular expression.</summary>
<returns>The character groups matched by the pattern.</returns>
val sampleLinks: string list
Multiple items
type RequestGate =
new: n: int -> RequestGate
member AsyncAcquire: ?timeout: int -> Async<IDisposable>
--------------------
new: n: int -> RequestGate
val semaphore: Semaphore
Multiple items
type Semaphore =
inherit WaitHandle
new: initialCount: int * maximumCount: int -> unit + 4 overloads
member Release: unit -> int + 1 overload
static member OpenExisting: name: string -> Semaphore + 1 overload
static member TryOpenExisting: name: string * result: byref<Semaphore> -> bool + 1 overload
<summary>Limits the number of threads that can access a resource or pool of resources concurrently.</summary>
--------------------
Semaphore(initialCount: int, maximumCount: int) : Semaphore
Semaphore(initialCount: int, maximumCount: int, name: string) : Semaphore
Semaphore(initialCount: int, maximumCount: int, name: string, options: NamedWaitHandleOptions) : Semaphore
Semaphore(initialCount: int, maximumCount: int, name: string, createdNew: byref<bool>) : Semaphore
Semaphore(initialCount: int, maximumCount: int, name: string, options: NamedWaitHandleOptions, createdNew: byref<bool>) : Semaphore
val timeout: int option
val ok: bool
static member Async.AwaitWaitHandle: waitHandle: WaitHandle * ?millisecondsTimeout: int -> Async<bool>
Semaphore.Release() : int
Semaphore.Release(releaseCount: int) : int
val webRequestGate: RequestGate
val crawlClient: HttpClient
Multiple items
type TimeSpan =
new: hours: int * minutes: int * seconds: int -> unit + 4 overloads
member Add: ts: TimeSpan -> TimeSpan
member CompareTo: value: obj -> int + 1 overload
member Divide: divisor: float -> TimeSpan + 1 overload
member Duration: unit -> TimeSpan
member Equals: value: obj -> bool + 2 overloads
member GetHashCode: unit -> int
member Multiply: factor: float -> TimeSpan
member Negate: unit -> TimeSpan
member Subtract: ts: TimeSpan -> TimeSpan
...
<summary>Represents a time interval.</summary>
--------------------
TimeSpan ()
TimeSpan(ticks: int64) : TimeSpan
TimeSpan(hours: int, minutes: int, seconds: int) : TimeSpan
TimeSpan(days: int, hours: int, minutes: int, seconds: int) : TimeSpan
TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int) : TimeSpan
TimeSpan(days: int, hours: int, minutes: int, seconds: int, milliseconds: int, microseconds: int) : TimeSpan
TimeSpan.FromSeconds(seconds: int64) : TimeSpan
TimeSpan.FromSeconds(value: float) : TimeSpan
TimeSpan.FromSeconds(seconds: int64, ?milliseconds: int64, ?microseconds: int64) : TimeSpan
val collectLinks: url: string -> Async<string list>
val holder: IDisposable
member RequestGate.AsyncAcquire: ?timeout: int -> Async<IDisposable>
HttpClient.GetAsync(requestUri: Uri) : Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string) : Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync(requestUri: Uri, cancellationToken: CancellationToken) : Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync(requestUri: Uri, completionOption: HttpCompletionOption) : Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string, cancellationToken: CancellationToken) : Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string, completionOption: HttpCompletionOption) : Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync(requestUri: Uri, completionOption: HttpCompletionOption, cancellationToken: CancellationToken) : Tasks.Task<HttpResponseMessage>
HttpClient.GetAsync( requestUri: string, completionOption: HttpCompletionOption, cancellationToken: CancellationToken) : Tasks.Task<HttpResponseMessage>
static member Async.AwaitTask: task: Tasks.Task -> Async<unit>
static member Async.AwaitTask: task: Tasks.Task<'T> -> Async<'T>
HttpContent.ReadAsStringAsync() : Tasks.Task<string>
HttpContent.ReadAsStringAsync(cancellationToken: CancellationToken) : Tasks.Task<string>
val links: string list
Multiple items
type List<'T> =
interface ICollection<'T>
interface seq<'T>
interface IEnumerable
interface IList<'T>
interface IReadOnlyCollection<'T>
interface IReadOnlyList<'T>
interface ICollection
interface IList
new: unit -> unit + 2 overloads
member Add: item: 'T -> unit
...
<summary>Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.</summary>
<typeparam name="T">The type of elements in the list.</typeparam>
--------------------
List() : List<'T>
List(collection: 'T seq) : List<'T>
List(capacity: int) : List<'T>
val length: list: 'T list -> int
val urlCollector: MailboxProcessor<string>
'urlCollector' is a single agent that receives URLs as messages. It creates new
asynchronous tasks that post messages back to this object.
Multiple items
type MailboxProcessor<'Msg> =
interface IDisposable
new: body: (MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken: CancellationToken -> MailboxProcessor<'Msg> + 1 overload
member Dispose: unit -> unit
member Post: message: 'Msg -> unit
member PostAndAsyncReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> Async<'Reply>
member PostAndReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> 'Reply
member PostAndTryAsyncReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> Async<'Reply option>
member Receive: ?timeout: int -> Async<'Msg>
member Scan: scanner: ('Msg -> Async<'T> option) * ?timeout: int -> Async<'T>
member TryPostAndReply: buildMessage: (AsyncReplyChannel<'Reply> -> 'Msg) * ?timeout: int -> 'Reply option
...
--------------------
new: body: (MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken: CancellationToken -> MailboxProcessor<'Msg>
new: body: (MailboxProcessor<'Msg> -> Async<unit>) * isThrowExceptionAfterDisposed: bool * ?cancellationToken: CancellationToken -> MailboxProcessor<'Msg>
static member MailboxProcessor.Start: body: (MailboxProcessor<'Msg> -> Async<unit>) * ?cancellationToken: CancellationToken -> MailboxProcessor<'Msg>
static member MailboxProcessor.Start: body: (MailboxProcessor<'Msg> -> Async<unit>) * isThrowExceptionAfterDisposed: bool * ?cancellationToken: CancellationToken -> MailboxProcessor<'Msg>
val self: MailboxProcessor<string>
val waitForUrl: visited: Set<string> -> Async<unit>
val visited: Set<string>
Multiple items
module Set
from Microsoft.FSharp.Collections
--------------------
type Set<'T (requires comparison)> =
interface IReadOnlyCollection<'T>
interface IStructuralEquatable
interface IComparable
interface IEnumerable
interface IEnumerable<'T>
interface ICollection<'T>
new: elements: 'T seq -> Set<'T>
member Add: value: 'T -> Set<'T>
member Contains: value: 'T -> bool
member IsProperSubsetOf: otherSet: Set<'T> -> bool
...
--------------------
new: elements: 'T seq -> Set<'T>
property Set.Count: int with get
member Set.Contains: value: 'T -> bool
static member Async.StartChild: computation: Async<'T> * ?millisecondsTimeout: int -> Async<Async<'T>>
val link: string
static member Async.Ignore: computation: Async<'T> -> Async<unit>
member Set.Add: value: 'T -> Set<'T>
val empty<'T (requires comparison)> : Set<'T> (requires comparison)
val parallelArrayInit: n: int -> f: (int -> 'a) -> 'a array
val f: (int -> 'a)
val currentLine: int ref
Multiple items
val ref: value: 'T -> 'T ref
--------------------
type 'T ref = Ref<'T>
val res: 'a array
val loop: unit -> unit
val y: int
type Interlocked =
static member Add: location1: byref<int> * value: int -> int + 3 overloads
static member And: location1: byref<int> * value: int -> int + 3 overloads
static member CompareExchange: location1: byref<float> * value: float * comparand: float -> float + 13 overloads
static member Decrement: location: byref<int> -> int + 3 overloads
static member Exchange: location1: byref<float> * value: float -> float + 13 overloads
static member Increment: location: byref<int> -> int + 3 overloads
static member MemoryBarrier: unit -> unit
static member MemoryBarrierProcessWide: unit -> unit
static member Or: location1: byref<int> * value: int -> int + 3 overloads
static member Read: location: inref<int64> -> int64 + 1 overload
<summary>Provides atomic operations for variables that are shared by multiple threads.</summary>
Interlocked.Increment(location: byref<uint64>) : uint64
Interlocked.Increment(location: byref<uint32>) : uint32
Interlocked.Increment(location: byref<int64>) : int64
Interlocked.Increment(location: byref<int>) : int
Ref.contents: int
type Environment =
static member Exit: exitCode: int -> unit
static member ExpandEnvironmentVariables: name: string -> string
static member FailFast: message: string -> unit + 1 overload
static member GetCommandLineArgs: unit -> string array
static member GetEnvironmentVariable: variable: string -> string + 1 overload
static member GetEnvironmentVariables: unit -> IDictionary + 1 overload
static member GetFolderPath: folder: SpecialFolder -> string + 1 overload
static member GetLogicalDrives: unit -> string array
static member SetEnvironmentVariable: variable: string * value: string -> unit + 1 overload
static member CommandLine: string
...
<summary>Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited.</summary>
property Environment.ProcessorCount: int with get
<summary>Gets the number of processors available to the current process.</summary>
<returns>The 32-bit signed integer that specifies the number of processors that are available.</returns>
val fib: x: int -> int
val x: int
val fibArray: int array
val t: Thread
type ThreadStart =
new: object: obj * method: nativeint -> unit
member BeginInvoke: callback: AsyncCallback * object: obj -> IAsyncResult
member EndInvoke: result: IAsyncResult -> unit
member Invoke: unit -> unit
<summary>Represents the method that executes on a <see cref="T:System.Threading.Thread" />.</summary>
property Thread.CurrentThread: Thread with get
<summary>Gets the currently running thread.</summary>
<returns>A <see cref="T:System.Threading.Thread" /> that is the representation of the currently running thread.</returns>
property Thread.ManagedThreadId: int with get
<summary>Gets a unique identifier for the current managed thread.</summary>
<returns>An integer that represents a unique identifier for this managed thread.</returns>
namespace System.Threading.Tasks
val doSome1Thing: unit -> unit
Thread.Sleep(timeout: TimeSpan) : unit
Thread.Sleep(millisecondsTimeout: int) : unit
val doSome2Thing: CancellationToken -> unit
Multiple items
type CancellationToken =
new: canceled: bool -> unit
member Equals: other: obj -> bool + 1 overload
member GetHashCode: unit -> int
member Register: callback: Action -> CancellationTokenRegistration + 4 overloads
member ThrowIfCancellationRequested: unit -> unit
member UnsafeRegister: callback: Action<obj,CancellationToken> * state: obj -> CancellationTokenRegistration + 1 overload
static member (<>) : left: CancellationToken * right: CancellationToken -> bool
static member (=) : left: CancellationToken * right: CancellationToken -> bool
member CanBeCanceled: bool
member IsCancellationRequested: bool
...
<summary>Propagates notification that operations should be canceled.</summary>
--------------------
CancellationToken ()
CancellationToken(canceled: bool) : CancellationToken
val doSome3Thing: ct: CancellationToken -> unit
val ct: CancellationToken
CancellationToken.ThrowIfCancellationRequested() : unit
val cts: CancellationTokenSource
Multiple items
type CancellationTokenSource =
interface IDisposable
new: unit -> unit + 3 overloads
member Cancel: unit -> unit + 1 overload
member CancelAfter: millisecondsDelay: int -> unit + 1 overload
member CancelAsync: unit -> Task
member Dispose: unit -> unit
member TryReset: unit -> bool
static member CreateLinkedTokenSource: token: CancellationToken -> CancellationTokenSource + 3 overloads
member IsCancellationRequested: bool
member Token: CancellationToken
<summary>Signals to a <see cref="T:System.Threading.CancellationToken" /> that it should be canceled.</summary>
--------------------
CancellationTokenSource() : CancellationTokenSource
CancellationTokenSource(millisecondsDelay: int) : CancellationTokenSource
CancellationTokenSource(delay: TimeSpan) : CancellationTokenSource
CancellationTokenSource(delay: TimeSpan, timeProvider: TimeProvider) : CancellationTokenSource