System.IO.MemoryStream.SetLength C# (CSharp) Method

SetLength() public method

public SetLength ( long value ) : void
value long
return void
        public override void SetLength(long value)
        {
            if (value < 0 || value > int.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
            }
            EnsureWriteable();

            // Origin wasn't publicly exposed above.
            Debug.Assert(MemStreamMaxLength == int.MaxValue);  // Check parameter validation logic in this method if this fails.
            if (value > (int.MaxValue - _origin))
            {
                throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
            }

            int newLength = _origin + (int)value;
            bool allocatedNewArray = EnsureCapacity(newLength);
            if (!allocatedNewArray && newLength > _length)
            {
                Array.Clear(_buffer, _length, newLength - _length);
            }

            _length = newLength;
            if (_position > newLength)
            {
                _position = newLength;
            }
        }

Usage Example

Exemplo n.º 1
0
        public async Task<Message> ReceiveAsync(CancellationToken cancellationToken = default(CancellationToken)) {
            const int blockSize = 0x10000;
            var buffer = new MemoryStream(blockSize);

            while (true) {
                cancellationToken.ThrowIfCancellationRequested();

                int index = (int)buffer.Length;
                buffer.SetLength(index + blockSize);

                await _receiveLock.WaitAsync(cancellationToken);
                WebSocketReceiveResult wsrr;
                try {
                    wsrr = await _socket.ReceiveAsync(new ArraySegment<byte>(buffer.GetBuffer(), index, blockSize), cancellationToken);
                } catch (Exception ex) when(IsTransportException(ex)) {
                    throw new MessageTransportException(ex);
                } finally {
                    _receiveLock.Release();
                }

                buffer.SetLength(index + wsrr.Count);

                if (wsrr.CloseStatus != null) {
                    return null;
                }

                if (wsrr.EndOfMessage) {
                    return Message.Parse(buffer.ToArray());
                }
            }
        }
All Usage Examples Of System.IO.MemoryStream::SetLength