C# 异步NamedPipeClientStream实现反馈

C# 异步NamedPipeClientStream实现反馈,c#,asynchronous,pipe,named,C#,Asynchronous,Pipe,Named,目前,我已经使用来自的演示代码实现了命名管道。而不是同步客户端;但是,我想让它异步。这是我的实现,主程序在其中调用StartClientNamedPipeListening(): // ///存储接收字节或接收字节的缓冲区 /// 专用字节[]_byteBuffer=null; /// ///从命名管道读取数据的回调结果 /// 私有IAsyncResult\u pipeResult; /// ///向看门狗发送和接收数据的命名对象 /// 命名为PipeClientStream\u

目前,我已经使用来自的演示代码实现了命名管道。而不是同步客户端;但是,我想让它异步。这是我的实现,主程序在其中调用StartClientNamedPipeListening():

//
///存储接收字节或接收字节的缓冲区
/// 
专用字节[]_byteBuffer=null;
/// 
///从命名管道读取数据的回调结果
/// 
私有IAsyncResult\u pipeResult;
/// 
///向看门狗发送和接收数据的命名对象
/// 
命名为PipeClientStream\u pipeClient;
/// 
///通知等待的线程已发生事件
/// 
受保护的ManualResetEvent _pipeReadDone=新的ManualResetEvent(错误);
私有对象_pipeState=新对象();
私有void StartClientNamedPipeListening()
{
//一根线穿过后,立即打开然后关闭闸门,
//即,将事件置于无信号或关闭状态:
_pipeReadDone.Reset();
//读取来自管道的数据并调用
//线程安全委托以获取接收到的数据。
_byteBuffer=新字节[50];
_pipeResult=\u pipeClient.BeginRead(\u byteBuffer,0,
_byteBuffer.Length,PipeReadCallback,_pipeState);
//这里有工作线程块(正在等待。。。
//_pipeReadDone.Set()),即等待开门
_pipeReadDone.WaitOne();
}
私有void PipeReadCallback(IAsyncResult ar)
{
int字节读取=0;
//如果串行端口打开且。。
如果(_pipeClient.IsConnected)
{
//然后流就可以读取了。。
if(_pipeClient.CanRead)
{
//等待异步读取完成
字节读取=_pipeClient.EndRead(ar);
}
}
如果(字节读取>0)
{
StreamString ss=新的StreamString(_pipeClient);
//验证服务器的签名字符串
如果(ss.ReadString()=“我是唯一真正的服务器!”)
{
//客户端安全令牌在第一次写入时发送。
//发送返回其内容的文件的名称
//通过服务器。
ss.WriteString(@“C:\Temp\namedpipestring.txt”);
//将文件打印到屏幕上。
Console.WriteLine(ss.ReadString(),false);
}
其他的
{
WriteLine(“无法验证服务器”);
}
//将事件置于有信号或打开的状态:
//为下一个数据打开门
_pipeReadDone.Set();
//开始等待下一条看门狗消息
StartClientNamedPipeListening();
}
}

这个实现根据我的测试工作;然而,我在想,我是不是在做一些明显的拒绝?有人对如何更好地实施该计划有什么建议吗?TIA。

下面是我如何修改代码以使其异步工作的。我不确定为什么我认为我需要手动重置事件:

    /// <summary>
    /// Buffer where received bytes or bytes received are stored 
    /// </summary>
    private byte[] _byteBuffer = null;

    /// <summary>
    /// Callback result for reading data from the named pipe
    /// </summary>
    private IAsyncResult _pipeResult;

    /// <summary>
    /// Named object to send and receive data to and from watchdog
    /// </summary>
    NamedPipeClientStream _pipeClient;

    private object _pipeState = new object();

    private void StartClientNamedPipeListening()
    {
            _pipeClient = new NamedPipeClientStream(".", "testpipe",
                PipeDirection.InOut, PipeOptions.Asynchronous,
                TokenImpersonationLevel.Impersonation);
            _pipeClient.Connect();
            // Reads the data coming in from the pipe and call the 
            // thread safe delegate to get the data received.
            _byteBuffer = new Byte[50];
            _pipeResult = _pipeClient.BeginRead(_byteBuffer, 0,
                _byteBuffer.Length, PipeReadCallback, _pipeState);      
    }

   private void PipeReadCallback(IAsyncResult ar)
    {
        int bytesRead = 0;

        // if port serial is open and..
        if (_pipeClient.IsConnected)
        {
            // the stream can read then..
            if (_pipeClient.CanRead)
            {
                // wait for asynchronous read to be completed
                bytesRead = _pipeClient.EndRead(ar);
            }
        }

        if (bytesRead > 0)
        {
            StreamString ss = new StreamString(_pipeClient);
            // Validate the server's signature string 
            if (ss.ReadString() == "I am the one true server!")
            {
                // The client security token is sent with the first write. 
                // Send the name of the file whose contents are returned 
                // by the server.
                ss.WriteString(@"C:\Temp\namedpipestring.txt");

                // Print the file to the screen.
                Console.WriteLine(ss.ReadString(), false);
            }
            else
            {
                Console.WriteLine("Server could not be verified.");
            }

            // Start waiting for the next watchdog message
            StartClientNamedPipeListening();
        }
    }
//
///存储接收字节或接收字节的缓冲区
/// 
专用字节[]_byteBuffer=null;
/// 
///从命名管道读取数据的回调结果
/// 
私有IAsyncResult\u pipeResult;
/// 
///向看门狗发送和接收数据的命名对象
/// 
命名为PipeClientStream\u pipeClient;
私有对象_pipeState=新对象();
私有void StartClientNamedPipeListening()
{
_pipeClient=新名称PipeClientStream(“.”,“testpipe”,
PipeDirection.InOut、PipeOptions.Asynchronous、,
TokenImpersonationLevel.Impersonation);
_连接();
//读取来自管道的数据并调用
//线程安全委托以获取接收到的数据。
_byteBuffer=新字节[50];
_pipeResult=\u pipeClient.BeginRead(\u byteBuffer,0,
_byteBuffer.Length,PipeReadCallback,_pipeState);
}
私有void PipeReadCallback(IAsyncResult ar)
{
int字节读取=0;
//如果串行端口打开且。。
如果(_pipeClient.IsConnected)
{
//然后流就可以读取了。。
if(_pipeClient.CanRead)
{
//等待异步读取完成
字节读取=_pipeClient.EndRead(ar);
}
}
如果(字节读取>0)
{
StreamString ss=新的StreamString(_pipeClient);
//验证服务器的签名字符串
如果(ss.ReadString()=“我是唯一真正的服务器!”)
{
//客户端安全令牌在第一次写入时发送。
//发送返回其内容的文件的名称
//通过服务器。
ss.WriteString(@“C:\Temp\namedpipestring.txt”);
//将文件打印到屏幕上。
Console.WriteLine(ss.ReadString(),false);
}
其他的
{
WriteLine(“无法验证服务器”);
}
//开始等待下一条看门狗消息
StartClientNamedPipeListening();
}
}

谢谢,Hans。

这似乎非常适合代码审查:我认为我没有特权移动它。你知道如何把这篇文章转移到那个论坛吗?当然,有一个明显的缺陷。使用BeginRead()然后阻塞直到收到响应完全没有意义。只需调用Read()。如果你想让它是异步的,那么这是不接近的,它的意思是“不要等待”。所以我应该去掉pi
    /// <summary>
    /// Buffer where received bytes or bytes received are stored 
    /// </summary>
    private byte[] _byteBuffer = null;

    /// <summary>
    /// Callback result for reading data from the named pipe
    /// </summary>
    private IAsyncResult _pipeResult;

    /// <summary>
    /// Named object to send and receive data to and from watchdog
    /// </summary>
    NamedPipeClientStream _pipeClient;

    private object _pipeState = new object();

    private void StartClientNamedPipeListening()
    {
            _pipeClient = new NamedPipeClientStream(".", "testpipe",
                PipeDirection.InOut, PipeOptions.Asynchronous,
                TokenImpersonationLevel.Impersonation);
            _pipeClient.Connect();
            // Reads the data coming in from the pipe and call the 
            // thread safe delegate to get the data received.
            _byteBuffer = new Byte[50];
            _pipeResult = _pipeClient.BeginRead(_byteBuffer, 0,
                _byteBuffer.Length, PipeReadCallback, _pipeState);      
    }

   private void PipeReadCallback(IAsyncResult ar)
    {
        int bytesRead = 0;

        // if port serial is open and..
        if (_pipeClient.IsConnected)
        {
            // the stream can read then..
            if (_pipeClient.CanRead)
            {
                // wait for asynchronous read to be completed
                bytesRead = _pipeClient.EndRead(ar);
            }
        }

        if (bytesRead > 0)
        {
            StreamString ss = new StreamString(_pipeClient);
            // Validate the server's signature string 
            if (ss.ReadString() == "I am the one true server!")
            {
                // The client security token is sent with the first write. 
                // Send the name of the file whose contents are returned 
                // by the server.
                ss.WriteString(@"C:\Temp\namedpipestring.txt");

                // Print the file to the screen.
                Console.WriteLine(ss.ReadString(), false);
            }
            else
            {
                Console.WriteLine("Server could not be verified.");
            }

            // Start waiting for the next watchdog message
            StartClientNamedPipeListening();
        }
    }