C#async/await方法到F#?

OJ *_*eño 11 f# c#-to-f#

我正在尝试学习F#,并且正在将一些C#代码转换为F#.

我有以下C#方法:

public async Task<Foo> GetFooAsync(byte[] content)
{
    using (var stream = new MemoryStream(content))
    {
        return await bar.GetFooAsync(stream);
    }
}
Run Code Online (Sandbox Code Playgroud)

bar一些私人领域在哪里并GetFooAsync返回一个Task<Foo>.

这如何转化为F#?

这是我目前拥有的:

member public this.GetFooAsync (content : byte[]) = 
    use stream = new MemoryStream(content)
    this.bar.GetFooAsync(stream)
Run Code Online (Sandbox Code Playgroud)

哪个返回一个Task.

Fyo*_*kin 12

在F#中,异步由async计算构建器表示,它不是一个精确的模拟Task,但通常可以用来代替一个:

member public this.GetFooAsync (content : byte[]) = 
   async {
      use stream = new MemoryStream(content) 
      return! this.bar.GetFooAsync(stream) |> Async.AwaitTask
   } 
   |> Async.StartAsTask
Run Code Online (Sandbox Code Playgroud)


der*_*asp 5

如果要将async/- await密集的C#代码转换为F#,由于F#async和之间的差异Task以及您始终必须调用的事实,可能会变得很麻烦Async.AwaitTask

为避免这种情况,您可以使用FSharpx库,该库具有一个task计算表达式。

let tplAsyncMethod p = Task.Run (fun _ -> string p)

// awaiting TPL method inside async computation expression
let asyncResult = async {
                   let! value1 = tplAsyncMethod 1 |> Async.AwaitTask
                   let! value2 = tplAsyncMethod 2 |> Async.AwaitTask
                   return value1 + value2
                }

// The same logic using task computation expression
open FSharpx.Task
let taskResult = task {
                    let! value1 = tplAsyncMethod 1
                    let! value2 = tplAsyncMethod 2
                    return value1 + value2
                }
Run Code Online (Sandbox Code Playgroud)

的结果asyncResultAsync<string>和的结果taskResultTask<string>