How do I await an async method in F#

旧街凉风 提交于 2019-12-22 04:08:13

问题


How do I await an async method in F#?

I have the following code:

 type LegoExample() = 

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

Error:

Unexpected binder keyword in member definition

Note, I reviewed the following link:

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


回答1:


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)

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

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.)

and then you could use this myAsyncComputation

  • 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
  • ...


来源:https://stackoverflow.com/questions/35522447/how-do-i-await-an-async-method-in-f

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