访问匿名管道时为什么会收到“无效的管道句柄”?

时间:2014-01-29 08:03:33

标签: c# pipe

我尝试在C#中使用匿名管道,但即使使用最基本的示例也是如此。这是服务器控制台应用程序:

namespace Server
{
    using System;
    using System.Diagnostics;
    using System.IO.Pipes;

    public static class Program
    {
        public static void Main()
        {
            using (var pipe = new AnonymousPipeServerStream(PipeDirection.In))
            {
                var pipeName = pipe.GetClientHandleAsString();

                var startInfo = new ProcessStartInfo("Client.exe", pipeName);
                startInfo.UseShellExecute = false;
                using (var process = Process.Start(startInfo))
                {
                    pipe.DisposeLocalCopyOfClientHandle();

                    var receivedByte = pipe.ReadByte();
                    Console.WriteLine(
                        "The client sent the following byte: " + receivedByte);

                    process.WaitForExit();
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

以下是控制台客户端应用的源代码:

namespace Client
{
    using System.IO.Pipes;

    public static class Program
    {
        public static void Main(string[] args)
        {
            using (var pipe = new AnonymousPipeClientStream(
                PipeDirection.Out, args[0]))
            {
                pipe.WriteByte(0x65);
            }
        }
    }
}

当我启动服务器时,客户端应用程序崩溃(Windows“客户端已停止工作”对话框)。服务器显示:

  

客户端发送以下字节:-1

     

Unhanded Exception:System.IO.IOException:管道句柄无效      在[...]
     at C:\ [...] \ Client \ Program.cs中的Client.program.Main(String [] args):第9行

我做错了什么?

1 个答案:

答案 0 :(得分:1)

找到它。而不是:

new AnonymousPipeServerStream(PipeDirection.In)

它应该是:

new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)