简体   繁体   中英

How do I write this async IO C# code in F#?

I have this code:

public async Task CreateFileAsync(string filePath, byte[] bytes)
    {
        using (var sourceStream = System.IO.File.Open(filePath, FileMode.OpenOrCreate))
        {
            sourceStream.Seek(0, SeekOrigin.End);
            await sourceStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
        }
    }

I want to write it on F#, I get as far as this before I can't figure out what to do:

module myModule
open System.IO;
let CreateFileAsync (filePath: string, bytes : byte[]) =
    use sourceStream = File.Open(filePath, FileMode.OpenOrCreate)
        |> sourceStream.Seek(0, SeekOrigin.End);        

I have searched around but there are a couple of concepts here and I can't put them all together.

You can use the async { .. } workflow:

let createFileAsync (filePath, bytes) = async {
  use sourceStream = System.IO.File.Open(filePath, FileMode.OpenOrCreate)
  sourceStream.Seek(0, SeekOrigin.End)
  do! sourceStream.AsyncWrite(bytes, 0, bytes.Length) }

This is fairly imperative code, so it does not look very different in F#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM