public static Task <int> ReceiveAsync(this RedisSocket socket, byte[] data, int offset, int count) { var tcs = new TaskCompletionSource <int>(socket); socket.GetRealStream().BeginRead(data, offset, count, ar => { var innerTcs = ar.DiscoverTaskCompletionSource <int>(); try { innerTcs.TrySetResult(((RedisSocket)innerTcs.Task.AsyncState).EndReceive(ar)); } catch (OperationCanceledException) { innerTcs.TrySetCanceled(); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return(tcs.Task); }
private int BeginReceive(RedisSocket socket, int length) { if ((length != 0) && socket.IsConnected() && (Interlocked.Read(ref m_ReadState) != RedisConstants.Zero) && (Interlocked.CompareExchange(ref m_ReceiveStarted, RedisConstants.One, RedisConstants.Zero) == RedisConstants.Zero)) { try { var availableLength = m_BufferSize - m_WritePosition; if (availableLength < 1) { Interlocked.Exchange(ref m_WritePosition, Beginning); Interlocked.Exchange(ref m_ReadPosition, Beginning); availableLength = m_BufferSize; } if (length > 0) { length = Math.Max(length, socket.Available); } var receiveSize = (length < 0) ? availableLength : Math.Min(length, availableLength); var timeout = false; var received = false; double receiveTimeout = m_ReceiveTimeout; var infiniteTimeout = (long)receiveTimeout == Timeout.Infinite; var stream = socket.GetRealStream(); var readStatus = SocketError.Success; do { try { var now = DateTime.UtcNow; var receivedLength = 0; if (!socket.UseSsl) { receivedLength = socket.Receive(m_Buffer, m_WritePosition, receiveSize, SocketFlags.None, out readStatus); } else { try { readStatus = SocketError.Success; receivedLength = stream.Read(m_Buffer, m_WritePosition, receiveSize); } catch (Exception e) { while (e != null) { e = e.InnerException; if (e is SocketException) { readStatus = ((SocketException)e).SocketErrorCode; break; } } if (readStatus != SocketError.Success) { throw; } } } if (readStatus == SocketError.TimedOut || readStatus == SocketError.WouldBlock) { if (!infiniteTimeout) { receiveTimeout -= (DateTime.UtcNow - now).TotalMilliseconds; if (receiveTimeout <= 0) { timeout = true; throw new SocketException((int)SocketError.TimedOut); } } continue; } received = true; if (receivedLength > 0) { IncrementWritePosition(receivedLength); } else if (receivedLength == 0) { Interlocked.Exchange(ref m_ReadState, RedisConstants.Zero); } return(receivedLength); } catch (SocketException e) { if (!infiniteTimeout || !(e.SocketErrorCode == SocketError.TimedOut || e.SocketErrorCode == SocketError.WouldBlock)) { throw; } } catch (Exception e) { if (!(e is SocketException)) { Interlocked.Exchange(ref m_ReceiveStarted, RedisConstants.Zero); } } }while (!(received || timeout) && (Interlocked.Read(ref m_ReadState) != RedisConstants.Zero)); } finally { Interlocked.Exchange(ref m_ReceiveStarted, RedisConstants.Zero); } } return(int.MinValue); }
public void Flush() { m_Socket.GetRealStream().Flush(); }