如何实现异步运行的可重用命名管道侦听器?

Mik*_*ras 6 .net asynchronous named-pipes reusability

我找不到一个很好的例子来说明如何创建一个异步运行的可重用命名管道侦听器.我可以做一个可重用的听众:

NamedPipeServerStream pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.InOut);

    while (true)
    {
            pipeServer.WaitForConnection();

            StreamReader reader = new StreamReader(pipeServer);

            MessageBox.Show(reader.ReadLine());

            pipeServer.Disconnect();
    }
Run Code Online (Sandbox Code Playgroud)

我可以做一个不常见的倾听者:

NamedPipeServerStream pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

    pipeServer.BeginWaitForConnection((a) =>
    {
        pipeServer.EndWaitForConnection(a);

        StreamReader reader = new StreamReader(pipeServer);
        MessageBox.Show(reader.ReadLine());

    }, null);
Run Code Online (Sandbox Code Playgroud)

但我似乎无法兼得.这有一个很好的例子吗?我也担心部分发送的消息,因为我认为这是异步通信的问题.

更新:我离我更近一点了.

pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

pipeServer.BeginWaitForConnection((a) =>
{
    pipeServer.EndWaitForConnection(a);

    StreamReader reader = new StreamReader(pipeServer);

    while (running)
    {
        String text = reader.ReadLine();

        if (String.IsNullOrEmpty(text) == false)
        {
            MessageBox.Show(text);
        }
    }

    MessageBox.Show("Done!");

}, null);
Run Code Online (Sandbox Code Playgroud)

这将成功读取一次,并将继续循环,ReadLine在初始成功读取后返回空的空字符串.所以它显然没有阻止,并试图再次阅读.问题是如果我第二次发送相同的消息,它不会被拾取,我的管道编写者说它收到错误2316(虽然我无法弄清楚这意味着什么).我想我只需要做一些类似于管道每次清理的事情,就像我列出的第一个代码示例一样,但我还没有完成工作.

Mik*_*ras 7

我想我已经得到了它:

pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);

Boolean connectedOrWaiting = false;

Byte[] buffer = new Byte[65535];

while (running)
{
    if (!connectedOrWaiting)
    {                   
        pipeServer.BeginWaitForConnection((a) => { pipeServer.EndWaitForConnection(a); }, null);

        connectedOrWaiting = true;
    }

    if (pipeServer.IsConnected)
    {
        Int32 count = pipeServer.Read(buffer, 0, 65535);

        if (count > 0)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String message = encoding.GetString(buffer, 0, count);

            MessageBox.Show(message);
        }

        pipeServer.Disconnect();

        connectedOrWaiting = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将接受多条消息,并在运行设置为false时立即关闭(显然在另一个线程中).这似乎是我需要的.有人可以证实我没有做任何愚蠢的事吗?