错误 F# - c# 异步调用:将 Threading.Tasks.Task<MyType> 转换为 Async<'a>

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

当我尝试从我的 F# 代码调用 C# 库中的异步方法时。 我收到以下编译错误。

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

SendMessageAsync 在 C# 库中并且 returns Threading.Thread.Tasks.Task<MyType>

let sendEmailAsync message = 
    async {
        let! response = client.SendMessageAsync(message)
        return response
    }

为了在 Task<'T>Async<'T> 之间进行转换,有一个内置的 Async.AwaitTask 函数。

要在普通 TaskAsync<unit> 之间转换,您可以创建一个辅助函数:

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

那么你可以这样称呼它:

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

当然,在这种情况下,响应只能是(),所以你不妨只写:

let sendEmailAsync message = Async.AwaitPlainTask <|client.SendMessageAsync(message)