C# async / await method to F#?

馋奶兔 提交于 2019-11-30 19:00:58

In F#, asynchrony is represented by the async computation builder, which is not an exact analog of Task, but can generally be used in place of one:

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

If you are converting async/await-intensive C# code to F#, it might get cumbersome because of the difference between F#'s async and Task and the fact that you always have to call Async.AwaitTask

To avoid that you can use FSharpx library, which has a task computation expression.

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
                }

The result of asyncResult is Async<string> and the result of taskResult is Task<string>.

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