Console.Error.WriteLineAsync() 与 Console.WriteLine,有什么区别。为什么后面会抛出异常?

问题描述 投票:0回答:0

我正在尝试理解 StreamJsonRpc 并从这里运行一个 示例

我在这里创建了一个淡化示例。它包含服务器和客户端,并通过 StreamJsonRpc 进行通信。

在服务器中,当我使用Console.WriteLine时,它会抛出异常。当我恢复使用 await Console.Error.WriteLineAsync() 时,它运行良好。

Exception is throw

这是为什么呢?看起来我缺少一些与等待异步有关的东西。

以下方法有效。

private static async Task RespondToRpcRequestsUsingConsoleErrorAsync(Stream stream, int clientId)
{
    await Console.Error.WriteLineAsync($"Connection request #{clientId} received. Spinning off an async Task to cater to requests.");
    var jsonRpc = JsonRpc.Attach(stream, new Server());
    await Console.Error.WriteLineAsync($"JSON-RPC listener attached to #{clientId}. Waiting for requests...");
    await jsonRpc.Completion;
    await Console.Error.WriteLineAsync($"Connection #{clientId} terminated.");
}

以下抛出异常。您可以在下面的Console.WriteLine()中看到替换上面的await Console.Error.WriteLineAsync()

private static async Task RespondToRpcRequestsUsingConsoleAsync(Stream stream, int clientId)
{
    Console.WriteLine($"Connection request #{clientId} received. Spinning off an async Task to cater to requests.");
    var jsonRpc = JsonRpc.Attach(stream, new Server());
    Console.WriteLine($"JSON-RPC listener attached to #{clientId}. Waiting for requests...");
    await jsonRpc.Completion;
    Console.WriteLine($"Connection #{clientId} terminated.");
}

我尝试使用 jsonRpc.Completion.Wait();jsonRpc.Completion.GetAwaiter().GetResult(); 如下,但没有成功。

private static void RespondToRpcRequestsUsingConsoleWithWait(Stream stream, int clientId)
{
    Console.WriteLine($"Connection request #{clientId} received. Spinning off an async Task to cater to requests.");
    var jsonRpc = JsonRpc.Attach(stream, new Server());
    Console.WriteLine($"JSON-RPC listener attached to #{clientId}. Waiting for requests...");
    jsonRpc.Completion.Wait(); // SEE HERE
    Console.WriteLine($"Connection #{clientId} terminated.");
}

private static void RespondToRpcRequestsUsingConsoleWithAwaiterAndResult(Stream stream, int clientId)
{
    Console.WriteLine($"Connection request #{clientId} received. Spinning off an async Task to cater to requests.");
    var jsonRpc = JsonRpc.Attach(stream, new Server());
    Console.WriteLine($"JSON-RPC listener attached to #{clientId}. Waiting for requests...");
    jsonRpc.Completion.GetAwaiter().GetResult(); // SEE HERE
    Console.WriteLine($"Connection #{clientId} terminated.");
}

如何运行示例。

  1. 只需在 Visual Studio 中打开 this,将客户端设置为启动项目,然后按 F5。
  2. 使用命令行,cd 进入客户端项目并运行它。
cd JsonRpcStdIoClient
dotnet run --project ./JsonRpcStdIoClient.csproj
.net asynchronous async-await
© www.soinside.com 2019 - 2024. All rights reserved.