我如何等待F#中的异步方法 [英] How do I await an async method in F#

查看:130
本文介绍了我如何等待F#中的异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何等待F#中的异步方法?

How do I await an async method in F#?

我有以下代码:

 type LegoExample() = 

    let brick = Brick(BluetoothCommunication("COM3"))
    let! result = brick.ConnectAsync();

错误:

成员定义中出现意外的活页夹关键字

Unexpected binder keyword in member definition

请注意,我查看了以下链接:

Note, I reviewed the following link:

但是,我只观察功能技术而不是OOP技术.

However, I only observe the functional technique and not the OOP technique.

推荐答案

,您会收到错误消息,因为let!构造(就像do!一样)需要放置在计算工作流程中(像async { ...}一样,但还有其他-它基本上是F#为单子提供的语法糖-在C#中,这是LINQ附带的from ... select ...东西,在Haskell中则是do ...块)

you get the error because the let! construct (just like the do!) needs to be placed inside a computational workflow (like async { ...} but there are others - it's basically the syntactic sugar F# gives you for monads - in C# it would be the from ... select ... stuff LINQ came with and in Haskell it would be do ... blocks)

因此,假设brick.ConnectAsync()确实会返回某些Async<...>,那么您可以像这样使用Async.RunSynchronously wait :

so assuming brick.ConnectAsync() will return indeed some Async<...> then you can wait for it using Async.RunSynchronously like this:

let brick = Brick(BluetoothCommunication("COM3"))
let result = brick.ConnectAsync() |> RunSynchronously

遗憾的是,在您链接的页面上进行的快速浏览器搜索未找到ConnectAsync,因此我无法确切告诉您代码段的缩进位置,但是您很可能希望将其包含在这样的async { ... }块中:

sadly a quick browser search on the page you linked did not find ConnectAsync so I cannot tell you exactly what the indent of the snippet was here but most likely you wanted to have this inside a async { ... } block like this:

let myAsyncComputation =
    async {
        let brick = Brick(BluetoothCommunication "COM3")
        let! result = brick.ConnectAsync()
        // do something with result ...
    }

(请注意,我删除了一些不必要的括号等)

(note that I remove some unnecessary parentheses etc.)

,然后您可以使用此myAsyncComputation

  • 在另一个async { .. }工作流程中
  • 使用Async.RunSynchronously运行并等待它
  • Async.Start一起在后台运行(为此,您的代码块必须输入Async<unit>类型
  • 使用Async.StartAsTask启动并从中获取Task<...>
  • ...
  • inside yet another async { .. } workflow
  • with Async.RunSynchronously to run and await it
  • with Async.Start to run it in background (your block needs to have type Async<unit> for this
  • with Async.StartAsTask to start and get a Task<...> out of it
  • ...

这篇关于我如何等待F#中的异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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