函数类型为'T - > Async <'T>,如C#的Task.FromResult

Ghi*_*102 6 f# asynchronous

我正在玩异步编程,并且想知道是否存在可以获取类型值'T并将其转换为类型的函数Async<'T>,类似于C#Task.FromResult,它可以获取类型的值TResult并将其转换为Task<TResult>可以等待的类型.

如果F#中不存在这样的功能,是否可以创建它?我可以通过使用Async.AwaitTask和Task.FromResult来模拟这个,但是我可以通过仅使用Async来实现吗?

从本质上讲,我希望能够做到这样的事情:

let asyncValue = toAsync 3 // toAsync: 'T -> Async<'T>

let foo = async{      
  let! value = asyncValue
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 8

您可以returnasync表达式中使用:

let toAsync x = async { return x }
Run Code Online (Sandbox Code Playgroud)

  • @ Ghi02如果你喜欢这个答案,请点击左边的苍白复选标记接受它. (3认同)

Sze*_*zer 6

...要不就 async.Return

let toAsync = async.Return
let toAsync` x = async.Return x
Run Code Online (Sandbox Code Playgroud)

而且有async.Bind(以tupled形式)

let asyncBind 
    (asyncValue: Async<'a>) 
    (asyncFun: 'a -> Async<'b>) : Async<'b> = 
    async.Bind(asyncValue, asyncFun)
Run Code Online (Sandbox Code Playgroud)

如果没有构建器gist链接,你可以使用它们来制作相当复杂的异步计算

let inline (>>-) x f = async.Bind(x, f >> async.Return)

let requestMasterAsync limit urls =
    let results = Array.zeroCreate (List.length urls)
    let chunks =
        urls
        |> Seq.chunkBySize limit
        |> Seq.indexed
    async.For (chunks, fun (i, chunk) -> 
        chunk 
        |>  Seq.map asyncMockup 
        |>  Async.Parallel
        >>- Seq.iteri (fun j r -> results.[i*limit+j]<-r))
    >>- fun _ -> results
Run Code Online (Sandbox Code Playgroud)