[英]Correctly awaiting in F# an async C# method with return type of Task<T>
[英]Implementing C# method returning Task<T> in F#
我在F#中創建了一個繼承自C#類的類型,該類公開了一個在C#中返回Task<T>
的方法。 我正在嘗試找出在F#中做到這一點的最佳方式
說我的C#看起來像這樣:
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
}
我在F#中繼承該類型的第一步看起來像這樣:
type Bar() =
inherits Foo()
override this.DoStuff() =
this.Out.WriteLineAsync("hey from F#") |> ignore
System.Threading.Task.FromResult(SomeEnum.Bar)
但是a)它不覺得它實際上是異步的並且b)它只是感覺不是-F#。
那么我將如何繼承Foo
類並實現期望返回Task<T>
的DoStuff
方法?
您可以使用Async.StartAsTask :
type Bar() =
inherit Foo()
override this.DoStuff() =
async { return SomeEnum.Bar } |> Async.StartAsTask
Async.StartAsTask
將Async<T>
作為輸入,並返回Task<T>
。
執行異步的F#方式是使用異步工作流 。 不幸的是, 他們不支持等待非通用Task
。 但是使用上述問題中的一個解決方法,您的代碼可能如下所示:
override this.DoStuff() =
async {
do! this.Out.WriteLineAsync("hey from F#") |> Async.AwaitVoidTask
return SomeEnum.Bar
} |> Async.StartAsTask
我相信FSharp包裝任務的方式就是使用
var a = Async.AwaitIAsyncResult(somecsharpreturningtask) |> ignore
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.