c#异步命名管道永远等待

本文关键字:管道 永远等待 异步 | 更新日期: 2023-09-27 18:11:39

我正在使用异步管道,并且在某些时候服务器和客户端相互等待并且什么都不做。下面是我的代码:

<标题>服务器:
var buffer = new byte[BufferSize];
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
    // Wait for client.
    Logger.Trace("Waiting for connection ...");
    var asyncResult = server.BeginWaitForConnection(a => { }, null);
     while (true)
     {
          await Task.Delay(MillisecondsDelay);
          if (asyncResult.IsCompleted) break;
      }
      server.EndWaitForConnection(asyncResult);
      Logger.Trace("Connection established.");

       using (var sr = new StreamReader(server))
       using (var sw = new StreamWriter(server))
       {
             // Send work.
             Logger.Trace("Sending operations...");
             await sw.WriteAsync(JsonConvert.SerializeObject(data));
             await sw.FlushAsync();
             server.WaitForPipeDrain();
              // Wait for response.
              var bytesRead = await server.ReadAsync(buffer, 0, buffer.Length);
       .....
<标题>客户:
        // Read data from the pipe...
 using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
 {
      Logger.Trace("Connecting to server...");
      client.Connect();
      Logger.Trace("Connected.");
      using (var sr = new StreamReader(client))
      using (var sw = new StreamWriter(client))
      {
           // Read operations.
           Logger.Trace("Waiting operations...");
           var text = await sr.ReadToEndAsync();
       .....

我记录的日志如下:

2016-10-04 16:09:51.5375 => (TRACE) | MyController.Execute : Waiting for connection ... |  
2016-10-04 16:09:52.0706 => (TRACE) | MyController+<Execute>d__5.MoveNext : Connection established. |  
2016-10-04 16:09:52.0706 => (TRACE) | MyController+<Execute>d__5.MoveNext : Sending operations... |  

:

2016-10-04 16:09:51.8486 => (TRACE) | EXE.Program.Process : Connecting to server... | 
2016-10-04 16:09:51.8696 => (TRACE) | EXE.Program.Process : Connected. | 
2016-10-04 16:09:51.8696 => (TRACE) | EXE.Program.Process : Waiting operations... | 

然后什么都没有!

之后就好像是死锁了。

我认为我应该在服务器或客户端每次写入后使用WaitForPipeDrain(),我这样做,但它似乎没有帮助。

客户端读操作永远不会返回。

有什么想法吗?

c#异步命名管道永远等待

我认为问题出在ReadToEndAsync方法上。StreamReader无法确定传输是否结束。例如,它可能是一个缓慢的连接,并且只发送了一半的数据。通常在这些情况下,您需要提出自己的"协议"来发送数据。有各种各样的方法,这里有几个:

  1. 等待结束符。我多次看到ASCII字符4用于此,因为它表示"EOT"(传输结束)。然而,这是基于这样一个假设,即您的消息不仅仅是可能包含该字符的二进制数据流。您可以将终止符改为一个序列,一些几乎从不的字符将出现在流中。

  2. 以将要发送的数据长度作为消息的前缀。例如,前4个字节总是的长度,抓取之后,您现在知道要读取多少。