Esempio n. 1
0
        public void BeginReceive(Action <Message> onMessage, Action <Exception> onError)
        {
            int end;

            if ((end = GetEndIndex()) >= 0)
            {
                onMessage(GetMessage(end));
                return;
            }

            EnsureReadBufferCapacity();
            channel.BeginRead(readBuffer, readCount, readBuffer.Length - readCount, OnReadCompleteWithErrorHandling, null);

            void OnReadCompleteWithErrorHandling(IAsyncResult asyncResult)
            {
                try
                {
                    OnReadComplete(asyncResult);
                }
                catch (System.IO.IOException exception)
                {
                    onError(exception);
                }
                catch (ObjectDisposedException exception)
                {
                    onError(exception);
                }
            }

            void OnReadComplete(IAsyncResult asyncResult)
            {
                var count = channel.EndRead(asyncResult);

                if (count == 0)
                {
                    OnLeave?.Invoke(this);
                    onError(new CantReadException());
                    return;
                }
                readCount += count;
                BeginReceive(onMessage, onError);
            }
        }