Implementing C# method returning Task<T> in F#

Deadly 提交于 2019-12-07 08:41:21

问题


I'm creating a type in F# that inherits from a C# class that exposes a method that returns Task<T> in C#. I'm trying to work out what'd be the best way to do that in F#

Say my C# looks like this:

public class Foo {
    public TextWriter Out { get { return Console.Out; } }

    public virtual Task<SomeEnum> DoStuff() {
        return Task.FromResult(SomeEnum.Foo);
    } 
}

public enum SomeEnum {
    Foo,
    Bar
}

My first pass of inheriting that type in F# looks like so:

type Bar() =
    inherits Foo()

    override this.DoStuff() =
        this.Out.WriteLineAsync("hey from F#") |> ignore

        System.Threading.Task.FromResult(SomeEnum.Bar)

But a) it doesn't feel like it's actually async and b) it just feels not-F#.

So how would I go about inheriting the Foo class and implement the DoStuff method that expects to return a Task<T>?


回答1:


You can use Async.StartAsTask:

type Bar() =
    inherit Foo()
    override this.DoStuff() =
        async { return SomeEnum.Bar } |> Async.StartAsTask

Async.StartAsTask takes Async<T> as input, and returns a Task<T>.




回答2:


The F# way of doing async is using asynchronous workflows. Unfortunately, they don't support awaiting non-generic Tasks. But using one of the workarounds from the above question, your code could look like this:

override this.DoStuff() =
    async {
        do! this.Out.WriteLineAsync("hey from F#") |> Async.AwaitVoidTask
        return SomeEnum.Bar
    } |> Async.StartAsTask



回答3:


I believe the FSharp way of wrapping over tasks is to use

var a = Async.AwaitIAsyncResult(somecsharpreturningtask) |> ignore


来源:https://stackoverflow.com/questions/30793392/implementing-c-sharp-method-returning-taskt-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!