开发者

Check for EOF in NamedPipeClientStream

开发者 https://www.devze.com 2023-03-23 01:59 出处:网络
With C functions it is possible to check if t开发者_运维技巧he output side of a pipe is empty via _eof(pipeOut) and skip the read operation.

With C functions it is possible to check if t开发者_运维技巧he output side of a pipe is empty via _eof(pipeOut) and skip the read operation.

int endOfFile = _eof(myPipeIn);
if(endOfFile != 0)
    int aReadCount = _read(myPipeIn, aBufferPtr, 256);

Is it possible to do something similar with .Net's NamedPipeClientStream?


Unfortunately Bueller's hint did not work for me, because ReadLine can block.

But with Zach's answer on Alternative to StreamReader.Peek and Thread.Interrupt I came up with the following:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool PeekNamedPipe(SafeHandle handle,
    byte[] buffer, uint nBufferSize, ref uint bytesRead,
    ref uint bytesAvail, ref uint BytesLeftThisMessage);

static bool SomethingToRead(SafeHandle streamHandle)
{
    byte[] aPeekBuffer = new byte[1];
    uint aPeekedBytes = 0;
    uint aAvailBytes = 0;
    uint aLeftBytes = 0;

    bool aPeekedSuccess = PeekNamedPipe(
        streamHandle,
        aPeekBuffer, 1,
        ref aPeekedBytes, ref aAvailBytes, ref aLeftBytes);

    if (aPeekedSuccess && aPeekBuffer[0] != 0)
        return true;
    else
        return false;
}

In my case the additional P/Invoke call is no problem.


According to the documentation http://msdn.microsoft.com/en-us/library/system.io.pipes.namedpipeclientstream.aspx there isn't a "peek" type of capability available on .Net pipes.

The methodology identified is to test the result of the read operation for NULL.

using (StreamReader sr = new StreamReader(pipeClient))
            {
                // Display the read text to the console
                string temp;
                while ((temp = sr.ReadLine()) != null)
                {
                    Console.WriteLine("Received from server: {0}", temp);
                }
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号