WaldiMen
WaldiMen

Reputation: 377

Using WriteLineAsync in F#

I am learning F# and I have problem with using WriteLineAsync.

With synchronous code it works perfectly:

using (new StreamWriter(new FileStream(@"c:\work\f2.txt",  FileMode.Create, FileAccess.Write, FileShare.None, bufferSize= 4096, useAsync= true)))
(fun sw -> File.ReadLines @"c:\Work\f1.txt" |> Seq.iter(fun x-> sw.WriteLine(x) ))

When I try to user WriteLineAsync:

using (new StreamWriter(new FileStream(@"c:\work\f2.txt",  FileMode.Create, FileAccess.Write, FileShare.None, bufferSize= 4096, useAsync= true)))
    (fun sw -> File.ReadLines @"c:\Work\f1.txt" |> Seq.iter(fun x-> sw.WriteLineAsync(x) |>  Async.AwaitTask |>  ignore ))

I got error InvalidOperationException:The stream writer is currently in use by a previous write operation.

What I am doing wrong ?

Upvotes: 3

Views: 439

Answers (1)

svick
svick

Reputation: 244767

All AwaitTask does is that it converts from Task<T> to Async<T>, it doesn't actually await anything. That means you can't just ignore the result.

What you can do is to create an async workflow and await WriteLineAsync() by using do!:

async {
    use sw = new StreamWriter(new FileStream(@"c:\work\f2.txt",  FileMode.Create, FileAccess.Write, FileShare.None, bufferSize= 4096, useAsync= true))
    for line in File.ReadLines @"c:\Work\f1.txt" do
        do! sw.WriteLineAsync(line) |>  Async.AwaitTask
}

Upvotes: 2

Related Questions