3

I am struggling to write an F# code that would sequentially await for some asynchronous method calls. I am familiar with F# async workflows but can't figure out how to map to it a simple case.

Let's take as an example an async XmlReader. Here's how the C# code might look:

using (XmlReader r = XmlReader.Create(new StringReader(input), new XmlReaderSettings() { Async = true }))
{
    while (await r.ReadAsync())
    {
        switch (r.NodeType)
        {
            case XmlNodeType.Element:
                Console.WriteLine(r.LocalName);
                break;

            case XmlNodeType.Text:
                Console.WriteLine(await r.GetValueAsync());
                break;
        }
    }
}

If this code didn't use async calls, we could just rewrite it in F# using recursion and pattern matching. But it uses ReadAsync and GetValueAsync, how they can be expressed in F# counterpart?

2

1 Answer 1

6

This is completely untested, but I think gets the point across. The essence of it is that you need to convert Task to Async using Async.AwaitTask then the rest of it is pretty obvious.

let doRecursiveAsyncThing input = async {
    use r = XmlReader.Create(new StringReader(input), new XmlReaderSettings(Async = true ))
    let loop x = async {
        let! noteType = r.ReadAsync() |> Async.AwaitTask
        match noteType with
        | XmlNodeType.Element -> Console.WriteLine r.LocalName
                                 do! loop x
        | XmlNodeType.Text    -> let! value = r.GetValueAsync() |> Async.AwaitTask
                                 Console.WriteLine value
                                 do! loop x
        | _                   -> () }

    }
    do! loop r
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! This is what I was trying to achieve. I missed Async.AwaitTask in my attempts to write similar code.
Note the helper function for async here: github.com/xamarin/shirt-store-fsharp/blob/master/Shared/…
The link is dead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.