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

时间:2016-10-04 13:29:28

标签: c# asynchronous named-pipes

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

服务器:

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()并且我这样做,但它似乎没有帮助。

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

任何想法?

1 个答案:

答案 0 :(得分:4)

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

  1. 等待终结者角色。很多时候我已经看到用于此的ASCII字符4,因为它意味着&#34; EOT&#34; (end of transmission)。但是,这是基于这样的假设,即您的消息不仅仅是可能包含该字符的二进制数据流。您可以将终结符改为序列,但几乎从不的几个字符将出现在流中。

  2. 使用您要发送的数据的长度作为前缀。例如,前4个字节总是长度,抓住后,你现在知道要阅读多少。