问题
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