How to Async.AwaitTask on plain Task (not Task<T>)?
You can use ContinueWith:
let awaitTask (t: Task) = t.ContinueWith (fun t -> ()) |> Async.AwaitTask
Or AwaitIAsyncResult with infinite timeout:
let awaitTask (t: Task) = t |> Async.AwaitIAsyncResult |> Async.Ignore
Update:
The FSharp.Core library for F# 4.0 now includes an Async.AwaitTask
overload that accepts a plain Task
. If you're using F# 4.0 then you should use this core function instead of the code below.
Original answer:
If your task could throw an exception then you probably also want to check for this. e.g.
let awaitTask (task : Task) =
async {
do! task |> Async.AwaitIAsyncResult |> Async.Ignore
if task.IsFaulted then raise task.Exception
return ()
}
Update:
The FSharp.Core library for F# 4.0 now includes an Async.AwaitTask overload that accepts a plain Task. If you're using F# 4.0 then you should use this core function instead of the code below.
Original answer:
I really liked Ashley's suggestion using function composition. Additionally, you can extend the Async module like this:
module Async =
let AwaitTaskVoid : (Task -> Async<unit>) =
Async.AwaitIAsyncResult >> Async.Ignore
Then it appears in Intellisense along with Async.AwaitTask. It can be used like this:
do! Task.Delay delay |> Async.AwaitTaskVoid
Any suggestions for a better name?