Search code examples
c#named-pipesasynccallback

How can I handle timeout when I read from namedpipeServerStream?


I have a namedpipeServerStream and I want to stop Reading its pipe when I meet the timeout.

these are my Read and Read callback function , and I call Read in my main program loop repeatedly, Actually my question is how can I call my callback function manually(or any other way)when timeout happened for endread.

 private void Read()
 {
       tmpBuff = new byte[600];
       inRead = true;
       ReadTimer.Enabled = true;
       len = 0;
       try
       {
            _namedpipeserver.BeginRead(tmpBuff, 0, 600, ReadCallback, null);
       }
       catch (Exception ex) //disconnected/disposed
       {
           return;
       }
 }

 static void ReadCallback(IAsyncResult ar)
 {
     int readbyte;
     try
     {
         readbyte = _namedpipeserver.EndRead(ar);
         if (readbyte > 0)
         {
             len = readbyte;
             int packetLen = tmpBuff[0] + (tmpBuff[1] * 256);
             Console.WriteLine(" packet len: " + packetLen + " bytes ");
             readbyte = 0;
             array = null;
             array = new byte[packetLen];
             Array.Copy(tmpBuff, 2, array, 0, packetLen);
         }
     }
     catch (IOException) //closed
     {
         return;
     }
     inRead = false;
 }

Any help Appreciated.Thanks


Solution

  • I resolved this problem by disposing connection after a defined timeout and waiting for other side of the pipe to connect again.

    Task.Run(() =>
    {
        tmpBuff = new byte[600];
        readbyte = _namedpipeserver.Read(tmpBuff, 0, 600);
    }).Wait(10000);
    
    if (readbyte <= 0)
        return null;
    

    In case null returned try to reinitiate pipe.