Search code examples
asynchronousiof#

Reading a file in an async context?


I would like to leverage async to make my code more readable and performant in F#.

I can read an entire file with a function like this:

let readFile path = async {
  return System.IO.File.ReadAllText path
}

And then use the function like this:

"README.md" |> readFile |> Async.RunSynchronously |> Console.WriteLine

However, the .NET ReadAllText method is blocking.

Is this an appropriate way to read files using async?


Solution

  • You can use the StreamReader class which exposes an asynchronous version of ReadToEnd.

    let readFile (path:string) = async {
      use sr = new StreamReader(path)
      return! sr.ReadToEndAsync() |> Async.AwaitTask
    }
    

    In practice, it is probably a good idea to run some measurements to make sure that you are actually getting some benefits from using async in this scenario - unless you are doing something interesting with many files, it might not matter much.


    Bonus:

    let writeFile (path : string) (content : string) = async {
      use sw = new System.IO.StreamWriter(path)
      return!
        sw.WriteAsync(content)
        |> Async.AwaitTask
    }