错误F#-c#异步调用:转换Threading.Tasks.Task< MyType>到异步 [英] Error F# - c# async calls : converting Threading.Tasks.Task<MyType> to Async<'a>

查看:66
本文介绍了错误F#-c#异步调用:转换Threading.Tasks.Task< MyType>到异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


该表达式的类型应为Async<'a>,但此处的类型为Threading .Thread.Tasks.Task

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

SendMessageAsync 在C#库中,并返回 Threading.Thread.Tasks.Task< MyType>

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

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


推荐答案

要在 Task<'T> Async<'T> 之间进行转换内置的 Async.AwaitTask 函数。

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

在普通 Task Async< unit> ,您可以创建一个辅助函数:

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)

这篇关于错误F#-c#异步调用:转换Threading.Tasks.Task&lt; MyType&gt;到异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆