Nishant Nidhi Kumar
Nishant Nidhi Kumar

Reputation: 93

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
    }

Upvotes: 9

Views: 1220

Answers (1)

TheInnerLight
TheInnerLight

Reputation: 12184

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)

Upvotes: 10

Related Questions