F# 6 introduced support for .NET tasks.
This snippet is shared everywhere - but what's the right way to call and use the result of the task (to e.g. printf
it)?
let readFilesTask (path1, path2) =
task {
let! bytes1 = File.ReadAllBytesAsync(path1)
let! bytes2 = File.ReadAllBytesAsync(path2)
return Array.append bytes1 bytes2
}
One option that works is:
let result = readFilesTask ("filaA", "fileB")
printf $"%A{result.Result}"
But is this the intended way of use?
There are a few ways to work with tasks. What is the "intended" way will depend on what you are trying to achieve.
Also note that for many applications, async
is only marginally slower but much easier to work with because it is "cold".
You can consume a task in another task using let!
and do!
:
task {
let! x = someOtherTask ()
do! andAnotherTask ()
return x
}
You can start a task and not wait on the result (fire and forget):
let foo () =
task {
printfn "Done."
}
foo () |> ignore // tasks are "hot" unlike asyncs
You can turn a task into an Async<'t>
using Async.AwaitTask
:
async {
do!
task {
printfn "Done."
}
|> Async.AwaitTask
}
You can block the current thread until a task is complete:
let foo () =
task {
printfn "Done."
}
let t = foo ()
t.Result
I expect that most real applications will have lots of do!
and let!
statements, but only a few .Result
calls in order to avoid blocking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With