2

I am trying to create the example class below (taken from here) in F#.

public class LoggingMiddleware
{
    private AppFunc next;

    public LoggingMiddleware(Func<IDictionary<string, object>, Task> next)
    {
        this.next = next;
    }

    public async Task Invoke(IDictionary<string, object> environment)
    {
        Console.WriteLine("Begin Request");
        await next.Invoke(environment);
        Console.WriteLine("End Request");
    }
}

However, I'm struggling both with converting between the typical .NET types and the typical F# types and using the F# async workflows to achieve what is happening with the C# await.

ShawnMartin
  • 282
  • 2
  • 7

1 Answers1

6

The biggest (current) issue with F# async workflows and .Net task is that there is no direct analogy to a Task that has no return type.

From this question, I'll use this function binding to await Tasks with no return value:

let awaitTask = Async.AwaitIAsyncResult >> Async.Ignore 

With that, you can directly translate your example class to:

type FSharpMiddleware(next: Func<IDictionary<string,obj>, Task>) =

    member this.Invoke (environment: IDictionary<string,obj>) : Task =
        async {
            printfn "Begin Request"
            do!
                awaitTask <| next.Invoke environment
            printfn "End Request"
        } |> Async.StartAsTask :> Task
Community
  • 1
  • 1
Christopher Stevenson
  • 2,843
  • 20
  • 25
  • This is *exactly* what I was looking for. Thank you! Hopefully it will help others dip their toes in the F# waters, too. – ShawnMartin Oct 24 '14 at 13:50