如何处理异步网络编程中的错误?

时间:2016-12-18 20:52:12

标签: c# asynchronous tcp network-programming

我有以下方法:

private void ClientReadCallback(IAsyncResult asyncResult)
        {
            try
            {
                var networkStream = _client.GetStream();
                var read = networkStream.EndRead(asyncResult);

                if (read == 0)
                {
                    Disconnected?.Invoke(this, new EventArgs());
                }

                byte[] buffer = asyncResult.AsyncState as byte[];
                if (buffer != null)
                {
                    byte[] data = new byte[read];
                    Buffer.BlockCopy(buffer, 0, data, 0, read);
                    networkStream.BeginRead(buffer, 0, buffer.Length, ClientReadCallback, buffer);
                    DataRead?.Invoke(this, new DataReadEventArgs(data));
                }
            }
            catch (Exception ex)
            {
                GetLog().Error(ex);
                ClientReadException?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }

触发a:System.ObjectDisposedException:无法在某些位置访问已处置的对象。

我的问题是:在哪种情况下会发生这种情况?网络问题?如何妥善处理? 感谢

0 个答案:

没有答案