Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error F# - c# async calls : converting Threading.Tasks.Task<MyType> to Async<'a>

When I try to call an async method that is in C# library from my F# code. I get the following compilation error.

This expression was expected to have type Async<'a> but here has type Threading.Thread.Tasks.Task

SendMessageAsync is in C# library and returns Threading.Thread.Tasks.Task<MyType>

let sendEmailAsync message = 
    async {
        let! response = client.SendMessageAsync(message)
        return response
    }
like image 448
Nishant Nidhi Kumar Avatar asked Apr 18 '17 15:04

Nishant Nidhi Kumar


1 Answers

For converting between Task<'T> and Async<'T> there is a built-in Async.AwaitTask function.

To convert between a plain Task and Async<unit> you can create a helper function:

type Async with
    member this.AwaitPlainTask (task : Task) =
        task.ContinueWith(fun t -> ())
        |> Async.AwaitTask

Then you can call it like this:

let sendEmailAsync message = 
    async {
        let! response = Async.AwaitPlainTask <|client.SendMessageAsync(message)
        return response
    }

Of course, in this case, the response can't be anything other than (), so you might as well just write:

let sendEmailAsync message = Async.AwaitPlainTask <|client.SendMessageAsync(message)
like image 73
TheInnerLight Avatar answered Nov 02 '22 04:11

TheInnerLight