Monday, August 19, 2013

F# asynchrony and Task -> Task<unit> conversion

Quite a number of useful library XxxXxxAsync methods return just plain Task objects, when what it means is that the synchronous operation has a void type. This causes a bit of a snag when calling from F#, as it expects the subclass Task<T> in the natural way of things. And there are no good hits on the topic of Task -> Task<unit> conversion -- so this is a compendium of the techniques that do the job.

So we can treat the Task as an IAsyncResult and use

to translate via an Async<Boolean> to Async<unit>; or convert the Task to a Task<unit> via a continuation and AwaitTask that

The latter, based on the helper awaitPlainTask method at, separating out the bit before you pipe it into Async.AwaitTask (then

by composition); this Ignore function is analogous to Async.Ignore, and can be used in that sort of role for all Task and Task<T> inputs. For example, in conjunction with the fsharpx Task computation expression, where it fills in a painful gap when faced with plain Tasks.

Post a Comment