private async Task <IDisposable> ReceiveLoop(IObserver <ArraySegment <byte> > observer) { var buffer = await _factory.Buffer.GetBufferAsync(); var awaitable = _factory.GetSocketAwaitable(); awaitable.SetBuffer(buffer, 0, buffer.Length); Exception completionException = null; try { while (_disposed == 0) { await _socket.ReceiveSocketAsync(awaitable); int count = awaitable.BytesTransferred; if (count == 0) { break; } observer.OnNext(new ArraySegment <byte>(buffer, 0, count)); } } catch (Exception ex) { completionException = ex; } finally { awaitable.Dispose(); _factory.Buffer.Return(buffer); try { if (completionException != null) { observer.OnError(completionException); } else { observer.OnCompleted(); } } catch (Exception) { //TODO: Log } } return(this); }
public Task Start() { ThrowIfDisposed(); var create = _createListenerFunc; if (Interlocked.CompareExchange(ref _createListenerFunc, null, create) != null) { try { _listenerSocket = create(); Events.Trace.CreateSocketListener(_listenerSocket.LocalEndPoint.ToString()); _awaitable = _socketAwaitableFactory.GetSocketAwaitable(); _startTcs.SetResult(_listenerSocket); } catch (Exception ex) { Events.Trace.Failure("Error creating socket listener." + ex.ToString()); _startTcs.SetException(ex); throw; } } return(_startTcs.Task); }