System.IO.StreamReader.ReadAsync C# (CSharp) Method

ReadAsync() public method

public ReadAsync ( char buffer, int index, int count ) : Task
buffer char
index int
count int
return Task
        public override Task<int> ReadAsync(char[] buffer, int index, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
            }
            if (index < 0 || count < 0)
            {
                throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if (buffer.Length - index < count)
            {
                throw new ArgumentException(SR.Argument_InvalidOffLen);
            }

            // If we have been inherited into a subclass, the following implementation could be incorrect
            // since it does not call through to Read() which a subclass might have overridden.  
            // To be safe we will only use this implementation in cases where we know it is safe to do so,
            // and delegate to our base class (which will call into Read) when we are not sure.
            if (GetType() != typeof(StreamReader))
            {
                return base.ReadAsync(buffer, index, count);
            }

            if (_stream == null)
            {
                throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
            }

            CheckAsyncTaskInProgress();

            Task<int> task = ReadAsyncInternal(buffer, index, count);
            _asyncReadTask = task;

            return task;
        }

Usage Example

Example #1
0
        private async Task logFromStream(Stream stream, CancellationToken token, string category, Func<bool> isComplete)
        {
            char[] buffer = new char[128];

            using (var sr = new StreamReader(stream))
            {
                while (true)
                {
                    token.ThrowIfCancellationRequested();

                    var outBytesRead = await sr.ReadAsync(buffer, 0, buffer.Length);

                    if (outBytesRead == 0)
                    {
                        if (isComplete())
                            break;
                        else
                            await Task.Delay(100);
                    }
                    else
                    {
                        var outText = new string(buffer, 0, outBytesRead);

                        if (!string.IsNullOrEmpty(outText))
                            this.newLogEntry(outText, category, true, true);
                    }
                }
            }
        }
All Usage Examples Of System.IO.StreamReader::ReadAsync