Can';从powershell ISE调用时,不能以异步C#代码写入控制台

Can';从powershell ISE调用时,不能以异步C#代码写入控制台,c#,.net,powershell,asynchronous,C#,.net,Powershell,Asynchronous,我有一个PowerShell脚本,需要调用C来完成工作,其中一些是异步的。在调试一些仅在从PowerShell调用C#代码时发生的错误时,我注意到了一些出乎意料的事情。在C#代码中,如果我调用了Console.WriteLine,它会按预期写入PowerShell控制台,除非我使用的是PowerShell ISE,并且在异步函数中执行等待后调用它 下面是显示问题的示例脚本: $source = @" using System; using System.Collections.Generic;

我有一个PowerShell脚本,需要调用C来完成工作,其中一些是异步的。在调试一些仅在从PowerShell调用C#代码时发生的错误时,我注意到了一些出乎意料的事情。在C#代码中,如果我调用了
Console.WriteLine
,它会按预期写入PowerShell控制台,除非我使用的是PowerShell ISE,并且在异步函数中执行等待后调用它

下面是显示问题的示例脚本:

$source = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

public class TestClass
{   
    public static int TestWrapper()
    {
        var task = TestAsync();
        task.Wait();
        return task.Result;
    }

    private static async Task<int> TestAsync()
    {
        Console.WriteLine("Before await");
        await Task.Run(() => { Thread.Sleep(2000); return; });
        Console.WriteLine("After await");
        return 2;
    }
}

"@

Add-Type -TypeDefinition $source
[TestClass]::TestWrapper()
这就是我在C#控制台应用程序或基本PowerShell中运行时看到的,但在PowerShell ISE中运行时,我看到:

Before await
2
有人能解释为什么会这样吗?

PowerShell ISE用于捕获和打印控制台。在PowerShell ISE主机窗口上写入线输出。只有在主机为当前线程注册()时,才能将主机文本写入程序重定向到PowerShell主机


在缺少同步上下文的情况下,
await
关键字导致的延续将在任意线程池中执行,该线程可能没有任何已注册的PowerShell主机重定向到控制台。WriteLine到。

在我尝试时效果很好。您知道,我不认为powershell和powershell ISE之间会有区别,但我想是的。啊,是的。我可以在运行PowerShell ISE时重现您的问题。这只是一个猜测,但控制台应用程序中是否有工作的SynchronizationContext?Powershell会弄糟吗?
Before await
2