每次调用SerialPort.BaseStream.EndRead()时都会发生IOException

时间:2015-03-16 15:52:31

标签: c# multithreading asynchronous serial-port

我尝试从串口异步获取数据。主要是因为DataReceived事件似乎不够可靠,我们最终得到了RXOver错误。 Target是.NET 4.0,因此我们需要使用较旧的Begin / End方法。

我还了解到需要在ThreadPool的一个线程中调用BeginRead(),否则在处理传递的回调时启动线程已经终止。

但是,即使使用池化线程,我始终也会获得IOException“由于线程退出或应用程序请求,I / O操作已中止”。 底层的com端口是打开的。

任何建议欢迎。

    #region DataReceiving

    private readonly byte[] buffer = new byte[MAX_BUFFER_SIZE];

    private void StartDataReceiving()
    {
        ThreadPool.QueueUserWorkItem( state => this.AsyncDataReceiving() );
    }

    private void AsyncDataReceiving()
    {
        this.serialPort.BaseStream.BeginRead(
            this.buffer, 0, this.buffer.Length,
            asyncResult =>
            {
                try
                {
                    int actualLength = this.serialPort.BaseStream.EndRead( asyncResult );
                    byte[] received = new byte[actualLength];
                    Buffer.BlockCopy( this.buffer, 0, received, 0, actualLength );

                    this.dataConsumer.Add( received );
                }
                catch (IOException ex)
                {
                    this.HandleSerialError( ex );
                }

                // Setup receiving action again
                this.AsyncDataReceiving();
            }
            , null );
    }

    #endregion

0 个答案:

没有答案