我正在尝试理解 StreamJsonRpc 并从这里运行一个 示例。
我在这里创建了一个淡化示例。它包含服务器和客户端,并通过 StreamJsonRpc 进行通信。
在服务器中,当我使用Console.WriteLine时,它会抛出异常。当我恢复使用 await Console.Error.WriteLineAsync() 时,它运行良好。
这是为什么呢?看起来我缺少一些与等待异步有关的东西。
以下方法有效。
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.");
}
cd JsonRpcStdIoClient
dotnet run --project ./JsonRpcStdIoClient.csproj