private void TimeoutHandler(object state) { AsyncState a = (AsyncState)state; _statesInFlight.TryRemove(a.Opaque, out _); a.Cancel(ResponseStatus.OperationTimeout); }
public Task SendAsync(byte[] request, Func <SocketAsyncState, Task> callback, ErrorMap errorMap) { var opaque = Converter.ToUInt32(request.AsSpan(HeaderOffsets.Opaque)); var state = new AsyncState { Opaque = opaque, Callback = callback, Converter = Converter, EndPoint = (IPEndPoint)EndPoint, ConnectionId = ContextId, ErrorMap = errorMap, LocalEndpoint = LocalEndPoint.ToString() }; _statesInFlight.TryAdd(state.Opaque, state); state.Timer = new Timer(o => { AsyncState a = (AsyncState)o; _statesInFlight.TryRemove(a.Opaque, out _); a.Cancel(ResponseStatus.OperationTimeout, new TimeoutException()); }, state, 75000, Timeout.Infinite); var sentBytesCount = 0; lock (Socket) { try { do { sentBytesCount += Socket.Send(request, sentBytesCount, request.Length - sentBytesCount, SocketFlags.None); } while (sentBytesCount < request.Length); } catch (Exception e) { HandleDisconnect(e); } } return(Task.FromResult(0)); }
public Task SendAsync(ReadOnlyMemory <byte> request, Func <SocketAsyncState, Task> callback, ErrorMap errorMap) { var opaque = Converter.ToUInt32(request.Span.Slice(HeaderOffsets.Opaque)); var state = new AsyncState { Opaque = opaque, Callback = callback, Converter = Converter, EndPoint = (IPEndPoint)EndPoint, ConnectionId = ConnectionId, ErrorMap = errorMap, LocalEndpoint = LocalEndPoint.ToString() }; _statesInFlight.TryAdd(state.Opaque, state); state.Timer = new Timer(o => { AsyncState a = (AsyncState)o; _statesInFlight.TryRemove(a.Opaque, out _); a.Cancel(ResponseStatus.OperationTimeout, new TimeoutException()); }, state, 75000, Timeout.Infinite); lock (Socket) { try { #if NETCOREAPP2_1 var requestSpan = request.Span; while (requestSpan.Length > 0) { var sentBytesCount = Socket.Send(requestSpan, SocketFlags.None); requestSpan = requestSpan.Slice(sentBytesCount); } #else if (!MemoryMarshal.TryGetArray <byte>(request, out var arraySegment)) { // Fallback in case we can't use the more efficient TryGetArray method arraySegment = new ArraySegment <byte>(request.ToArray()); } var sentBytesCount = 0; do { // ReSharper disable once AssignNullToNotNullAttribute sentBytesCount += Socket.Send(arraySegment.Array, arraySegment.Offset + sentBytesCount, arraySegment.Count - sentBytesCount, SocketFlags.None); } while (sentBytesCount < arraySegment.Count); #endif } catch (Exception e) { HandleDisconnect(e); } } return(Task.FromResult(0)); }