问题描述
我在F#以下code:
I have the following code in F#:
let CreateSampleDataFromJson<'T>(path) =
let uri = new Uri(path)
async {
let file = StorageFile.GetFileFromApplicationUriAsync(uri)
let jsonText = FileIO.ReadTextAsync(file)
return JsonObject<'T>.Parse(jsonText)
}
我遇到的问题是,文件
是 IAsyncOperation&LT; StorageFile&GT;
,而不是 StorageFile
为 ReadTextAsync
预计。
在C#中,你可以做一些类似的:
In C# you can do something similar to this:
var file = await StorageFile.GetFileFromApplicationUriAsync(uri)
即
public async Task<T> CreateSampleDataFromUrl<T>(string path)
{
var uri = new Uri(path);
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
var jsonText = await FileIO.ReadTextAsync(file);
return JsonObject<T>.Parse(jsonText);
}
问题是,我不知道如何等待一个 IAsyncOperation
F#中。通常让!
不起作用。即以下编译失败:
The problem is that I don't know how to await an IAsyncOperation
in F#. The usual let!
doesn't work. i.e. the following fails to compile:
async {
let! file = StorageFile.GetFileFromApplicationUriAsync(uri)
通过编译器错误:
error FS0001: This expression was expected to have type Async<'a> but here has type IAsyncOperation<StorageFile>
我发现了一份文件,称有一个在 System.WindowsRuntimeSystemExtensions
类中定义的 AsTask()
扩展方法,我可以使用如下:
I found a document that said there's an AsTask()
extension method defined in the System.WindowsRuntimeSystemExtensions
class which I can use as follows:
let! file = StorageFile.GetFileFromApplicationUriAsync(uri).AsTask() |> Async.AwaitTask
有没有使这是一个更好一点的地方这样做,或可用的东西在F#库的标准方式?
Is there a standard way of doing this or something available in an F# library somewhere that makes this a bit nicer?
推荐答案
您的解决方案由我似乎罚款。如果你正在寻找一个更好的语法,如何滚动它变成这样的功能(没有可能无偿类型注释):
Your solution seems fine by me. If you're looking for a nicer syntax, how about rolling it into a function like this (without the possibly gratuitous type annotations):
let await<'a> (op: IAsyncOperation<'a>) : Async<'a> =
op.AsTask() |> Async.AwaitTask
这会给你你会在C#中看到几乎相同的语法:
This will give you the almost exact same syntax you'd see in c#:
async {
let! file = await <| StorageFile.GetFileFromApplicationUriAsync(uri)
...
}
您与您的previous方法被越来越编译器错误是可以预期的。所有异步工作流程在乎的是F#异步特异型。这种类型给你一个的方式与.NET世界中通过任务其余的互操作,但仅此而已。 IAsyncOperation是从'世界不同部分',我不希望F#核心库很快支持。
The compiler errors you were getting with your previous approaches are to be expected. All async workflow cares about is the F#-specific Async type. This type gives you a way to interop with the rest of .NET world through Tasks, but that's it. IAsyncOperation is from a 'different part of the world', I wouldn't expect F# core libraries to support it anytime soon.
这篇关于等待在F#的IAsyncOperation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!