public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { var ar = new AsyncResult<int>(callback, state); Action closedHandler = null; closedHandler = () => { lock (_lockObj) { if (!ar.IsCompleted) { // Set the response to 0 if we've closed ar.SetAsCompleted(0, false); } _onClosed -= closedHandler; } }; _onClosed += closedHandler; if (CancellationToken.IsCancellationRequested) { ar.SetAsCompleted(0, true); return ar; } int read = Read(buffer, offset, count); if (read != 0 || CancellationToken.IsCancellationRequested) { lock (_lockObj) { if (!ar.IsCompleted) { ar.SetAsCompleted(read, true); } } } else { Action writeHandler = null; writeHandler = () => { lock (_lockObj) { if (!ar.IsCompleted) { read = Read(buffer, offset, count); ar.SetAsCompleted(read, false); } _onWrite -= writeHandler; } }; _onWrite += writeHandler; } return ar; }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { var ar = new AsyncResult <int>(callback, state); Action closedHandler = null; closedHandler = () => { lock (_lockObj) { if (!ar.IsCompleted) { // Set the response to 0 if we've closed ar.SetAsCompleted(0, false); } _onClosed -= closedHandler; } }; _onClosed += closedHandler; if (Ended) { ar.SetAsCompleted(0, true); return(ar); } int read = Read(buffer, offset, count); if (read != 0 || Ended) { lock (_lockObj) { if (!ar.IsCompleted) { ar.SetAsCompleted(read, true); } } } else { Action writeHandler = null; writeHandler = () => { lock (_lockObj) { if (!ar.IsCompleted) { read = Read(buffer, offset, count); ar.SetAsCompleted(read, false); } _onWrite -= writeHandler; } }; _onWrite += writeHandler; } return(ar); }