Exemple #1
0
        private static ValueTask <int> WritePacketAsync(IByteHandler byteHandler, int sequenceNumber, ArraySegment <byte> contents, IOBehavior ioBehavior)
        {
            var bufferLength = contents.Count + 4;
            var buffer       = ArrayPool <byte> .Shared.Rent(bufferLength);

            SerializationUtility.WriteUInt32((uint)contents.Count, buffer, 0, 3);
            buffer[3] = (byte)sequenceNumber;
            Buffer.BlockCopy(contents.Array, contents.Offset, buffer, 4, contents.Count);
            var task = byteHandler.WriteBytesAsync(new ArraySegment <byte>(buffer, 0, bufferLength), ioBehavior);

            if (task.IsCompletedSuccessfully)
            {
                ArrayPool <byte> .Shared.Return(buffer);

                return(default(ValueTask <int>));
            }
            return(AddContinuation(task, buffer));

            // NOTE: use a local function (with no captures) to defer creation of lambda objects
            ValueTask <int> AddContinuation(ValueTask <int> task_, byte[] buffer_)
            {
                return(task_.ContinueWith(x =>
                {
                    ArrayPool <byte> .Shared.Return(buffer_);
                    return default(ValueTask <int>);
                }));
            }
        }
Exemple #2
0
        private static ValueTask <int> WritePacketAsync(IByteHandler byteHandler, int sequenceNumber, ArraySegment <byte> contents, IOBehavior ioBehavior)
        {
            var bufferLength = contents.Count + 4;
            var buffer       = ArrayPool <byte> .Shared.Rent(bufferLength);

            SerializationUtility.WriteUInt32((uint)contents.Count, buffer, 0, 3);
            buffer[3] = (byte)sequenceNumber;
            Buffer.BlockCopy(contents.Array, contents.Offset, buffer, 4, contents.Count);
            var task = byteHandler.WriteBytesAsync(new ArraySegment <byte>(buffer, 0, bufferLength), ioBehavior);

            if (task.IsCompletedSuccessfully)
            {
                ArrayPool <byte> .Shared.Return(buffer);

                return(default);