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

这一生的挚爱 提交于 2020-02-24 05:06:09

问题


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
    }

回答1:


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)


来源:https://stackoverflow.com/questions/43476042/error-f-c-sharp-async-calls-converting-threading-tasks-taskmytype-to-asyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!