所以我试图采用一种IAsyncEnumerable
方法并在 PowerShell 中传递所述方法的结果。我知道 PowerShell 没有异步支持,通常,人们使用它Task.GetAwaiter().GetResult()
作为获得结果的手段。
但是,这种方法对方法不起作用(或者至少我不知道如何实现它)IAsyncEnumerable
。
我的具体情况要复杂一些,但让我们举个例子:
namespace ServerMetadataCache.Client.Powershell
{
[Cmdlet(VerbsDiagnostic.Test,"SampleCmdlet")]
[OutputType(typeof(FavoriteStuff))]
public class TestSampleCmdletCommand : PSCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
public int FavoriteNumber { get; set; } = default!;
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true)]
[ValidateSet("Cat", "Dog", "Horse")]
public string FavoritePet { get; set; } = "Dog";
private IAsyncEnumerable<int> InternalMethodAsync()
{
for (int i = 1; i <= 10; i++)
{
await Task.Delay(1000);//Simulate waiting for data to come through.
yield return i;
}
}
protected override void EndProcessing()
{
//this is the issue... how can I tell powershell to read/process results of
//InternalMethodAsync()? Regularly trying to read the method doesn't work
//and neither does wrapping the method with a task and using GetAwaiter().GetResult()
}
public class FavoriteStuff
{
public int FavoriteNumber { get; set; } = default!;
public string FavoritePet { get; set; } = default!;
}
}
这个 cmdlet 当然是一个虚拟的,只接受一个整数和“狗”、“猫”或“马”,但我更关心的是如何InternalMethodAsync()
在 Cmdlet 中处理。挑战在于绕过IAsyncEnumerable
.