示例#1
0
        internal void BeginRead()
        {
            if (inputBuffer == null)
            {
                inputBuffer = new byte[1024 * 4];
            }

            while (true)
            {
                if (!state.CanRead())
                {
                    return;
                }

                int          read;
                Exception    error;
                IAsyncResult ar0 = null;

                Debug.WriteLine("KayakSocket: reading.");

                try
                {
                    ar0 = socket.BeginReceive(inputBuffer, 0, inputBuffer.Length, ar =>
                    {
                        if (ar.CompletedSynchronously)
                        {
                            return;
                        }

                        read = EndRead(ar, out error);

                        // small optimization
                        if (error is ObjectDisposedException)
                        {
                            return;
                        }

                        scheduler.Post(() =>
                        {
                            Debug.WriteLine("KayakSocket: receive completed async");

                            if (error != null)
                            {
                                HandleReadError(error);
                            }
                            else
                            {
                                if (!HandleReadResult(read, false))
                                {
                                    BeginRead();
                                }
                            }
                        });
                    });
                }
                catch (Exception e)
                {
                    HandleReadError(e);
                    break;
                }

                if (!ar0.CompletedSynchronously)
                {
                    break;
                }

                Debug.WriteLine("KayakSocket: receive completed sync");
                read = EndRead(ar0, out error);

                if (error != null)
                {
                    HandleReadError(error);
                    break;
                }
                else
                {
                    if (HandleReadResult(read, true))
                    {
                        break;
                    }
                }
            }
        }