I'm trying to consume a C# library in F#. The library makes heavy use of async/await. I want to use within an async { ... }
workflow in F#.
I see we can Async.AwaitTask
on async C# methods returning Task<T>
, but what about those returning plain Task
?
Perhaps, is there a helper to convert these to Async<unit>
or to convert Task
to Task<unit>
so it will work with Async.AwaitTask
?
You can use ContinueWith:
Or AwaitIAsyncResult with infinite timeout:
To properly propagate both exceptions and cancellation properly, I think you need something like this (partially based on deleted answer by Tomáš Petříček):
Update:
The FSharp.Core library for F# 4.0 now includes an
Async.AwaitTask
overload that accepts a plainTask
. 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.
I really liked Ashley's suggestion using function composition. Additionally, you can extend the Async module like this:
Then it appears in Intellisense along with Async.AwaitTask. It can be used like this:
Any suggestions for a better name?