public int Receive(Memory<byte> buffer) { // This can work with Span<byte> because it's synchronous but we need pinning support unsafe { ArraySegment<byte> segment; if (buffer.TryGetArray(out segment)) { return Receive(segment); } else { void* pointer; buffer.TryGetPointer(out pointer); return ReceivePinned(new IntPtr(pointer), buffer.Length); } } }
// unsafe+async not good friends private unsafe void SetBuffer(Memory<byte> memory, SocketAsyncEventArgs args, int ignore = 0) { ArraySegment<byte> segment; if (!memory.TryGetArray(out segment)) { throw new InvalidOperationException("Memory is not backed by an array; oops!"); } args.SetBuffer(segment.Array, segment.Offset + ignore, segment.Count - ignore); }