[英]F# async lambda interop with C# async model
I have such a piece of code (C#, Pulumi), which I want to translate to F#:我有这么一段代码(C#、Pulumi),我想把它翻译成 F#:
var registryInfo = repo.RegistryId.Apply(async (id) =>
{
var creds = await GetCredentials.InvokeAsync(new GetCredentialsArgs {RegistryId = id});
var decodedData = Convert.FromBase64String(creds.AuthorizationToken);
var decoded = ASCIIEncoding.ASCII.GetString(decodedData);
var parts = decoded.Split(':');
return new ImageRegistry
{
Server = creds.ProxyEndpoint,
Username = parts[0],
Password = parts[1],
};
});
What I have managed to do so far is:到目前为止我设法做的是:
let registryInfo = repo.RegistryId.Apply (fun id -> async {
let! creds = GetCredentialsArgs ( RegistryId = id) |> GetCredentials.InvokeAsync |> Async.AwaitTask
let decodedData = Convert.FromBase64String creds.AuthorizationToken
let decoded = ASCIIEncoding.ASCII.GetString decodedData
let parts = decoded.Split ':'
return ImageRegistry( Server = input creds.ProxyEndpoint, Username= input parts.[0], Password = input parts.[1])
}
)
The problem is that the code above in F# returns Output<Async<ImageRegistry>>
, while C# code returns expected Output<ImageRegistry>
.问题是上面的 F# 代码返回
Output<Async<ImageRegistry>>
,而 C# 代码返回预期的Output<ImageRegistry>
。 I am doing a transition from C# to F# (to extend my skills), but I cannot handle this case myself.我正在从 C# 过渡到 F#(以扩展我的技能),但我自己无法处理这种情况。 How this should be properly done?
这应该如何正确完成?
The library Pulumi.FSharp
provides a useful helper Outputs.applyAsync
for this:库
Pulumi.FSharp
提供了一个有用的帮助程序Outputs.applyAsync
:
open Pulumi.FSharp
let registryInfo =
repo.RegistryId |>
Outputs.applyAsync (fun id -> async {
let! creds = GetCredentialsArgs ( RegistryId = id) |> GetCredentials.InvokeAsync |> Async.AwaitTask
let decodedData = Convert.FromBase64String creds.AuthorizationToken
let decoded = ASCIIEncoding.ASCII.GetString decodedData
let parts = decoded.Split ':'
return ImageRegistry( Server = input creds.ProxyEndpoint, Username= input parts.[0], Password = input parts.[1])
})
Without knowing too much about the Pulimu API's I'd guess that Apply
is expecting a Task<T>
.在不太了解 Pulimu API 的情况下,我猜想
Apply
期待的是Task<T>
。
You can convert from F# async to Task using Async.StartAsTask
like so:您可以使用
Async.StartAsTask
从 F# async 转换为 Task ,如下所示:
let registryInfo = repo.RegistryId.Apply (fun id -> async {
//snip
return ImageRegistry( Server = input creds.ProxyEndpoint, Username= input parts.[0], Password = input parts.[1])
} |> Async.StartAsTask
)
Although if you are working with Task's you might be better using the task
computation expression over the native F# async
using a library such as Ply (as of writing the native task support is still in development ).尽管如果您正在使用 Task 的工作,您可能会更好地使用
task
计算表达式而不是使用Ply等库的本机 F# async
(截至编写本机任务支持仍在开发中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.