c# - 检查 NamedPipeClientStream 中的 EOF

标签 c# pipe

使用 C 函数可以通过 _eof(pipeOut) 检查管道的输出端是否为空并跳过读取操作。

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

是否可以使用 .Net 的 NamedPipeClientStream 做类似的事情?

最佳答案

不幸的是,Bueller 的提示对我不起作用,因为 ReadLine 可以阻塞。

但是 Zach 在 Alternative to StreamReader.Peek and Thread.Interrupt 上的回答我想出了以下内容:

[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;
}

在我的例子中,额外的 P/Invoke 调用没有问题。

关于c# - 检查 NamedPipeClientStream 中的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6846365/

相关文章:

c# - 在ASP.NET MVC4中,如何重定向到{controller}/{id}?

c# - 用 IDisposable 包装互斥锁并测试它,但测试永远不会结束

c# - 具有多个参数的 SignalR 客户端

bash - 如何将多个命令通过管道传输到 shell 中的单个命令? (嘘,庆典,...)

c - 超过 2 个子节点之间的管道失败 - C

linux - 如何从管道结果中提取文件名?

c# - 如何使用 word interop 一次将一个项目添加到 word 文档的新行

c# - 属性在 C# 中实际上是如何工作的,例如 DateTime.Today?

Angular2 Dart 英雄之旅 : uppercase

c - 简单的 PIPE 程序会读取奇怪的字符