Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 999
sdgfsdh Avatar asked Jan 29 '23 00:01

sdgfsdh


1 Answers

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
}
like image 118
Tomas Petricek Avatar answered Jan 30 '23 12:01

Tomas Petricek