C # async / await method for F #?

I am trying to learn F # and in the process of converting some C # code to F #.

I have the following C # method:

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

Where bar- this is some kind of private field, but GetFooAsyncreturns Task<Foo>.

How to translate this to F #?

Here is what I have now:

member public this.GetFooAsync (content : byte[]) = 
    use stream = new MemoryStream(content)
    this.bar.GetFooAsync(stream)

Returns a Task.

+4
source share
2 answers

In F #, asynchrony is represented by a constructor of calculations async, which is not an exact analogue Task, but can usually be used instead of one:

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

async/await - # 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
                }

asyncResult Async<string>, taskResult Task<string>.

+2

Source: https://habr.com/ru/post/1659509/


All Articles