TcpClient.ConnectAsync or BeginConnect/EndConnect in F# async workflow

asynchronous, f#

Solution

Take a look at `Async.AwaitTask` and `Async.FromBeginEnd`.

Generally this will work:

async {
  ...
  do! client.ConnectAsync(address, port) |> Async.AwaitTask
}

However, because the `Async` module only works directly with `Task<'T>` and `ConnectAsync` returns `Task`, the code required in this particular case is slightly longer:

do! client.ConnectAsync(address, port) |> Async.AwaitIAsyncResult |> Async.Ignore

or

let! _ = client.ConnectAsync(address, port) |> Async.AwaitIAsyncResult

Problem

TcpClient.ConnectAsync is a Task, which doesn't work readily with F# async workflows. I think I'm missing something really simple here -- is there a general way to use either the Async or Begin/End functions from workflows?

Original source