Asynchronous stream reader with progress bar support
Asynchronous stream reader with progress bar support.
Introduction
This piece of code does async stream reading enabling you to use a progress bar in your application. On every byte read, it fires an event that contains the percentage of current read progress.
This is just an idea of how to make an async reader, so if you have any suggestions on how make it better or faster, let me now.
Using the code
The following are the AsyncStreamReader
events:
EventHandler<AsyncReadEventArgs> OnReadedBytes
- Occurs when the byte is read from theSystem.IO.StreamReader
, and contains the percentage of total read bytes.EventHandler<AsyncReadEventArgs> OnEndRead
- Occurs when all bytes are read from theSystem.IO.StreamReader
and contains the byte array of the read content.EventHandler<AsyncReadErrorEventArgs> OnError
- Occurs when anAsyncStream.AsyncExcpetion
happens and contains the exception.EventHandler<AsyncStreamStateChangeArgs> OnStateChanged
- Occurs when the state ofAsyncStream.AsyncStreamReader
changes and contains the current state.
The following are the AsyncStreamReader public properties:
AsyncStreamState State
- Specifies the identifiers to indicate the the state ofAsyncStream.AsyncStreamReader
.string Path
- Gets the complete file path to be read.
The following are the AsyncStreamReader
pubic methods:
BeginRead()
- Begins an asynchronous read operation and sets the state toStarted
.StopRead()
- Stops an asynchronous read operation and sets the state toStopped
.PauseRead()
- Pauses an asynchronous read operation and sets the state toPaused
.ResumeRead()
- Resumes a paused asynchronous read operation and sets the state back toStarted
.
This is how we create a new asynchronous stream:
AsyncStreamReader reader = new AsyncStreamReader(fileName);
reader.OnReadedBytes += new EventHandler<AsyncReadEventArgs>(reader_OnReadedBytes);
reader.OnEndRead += new EventHandler<AsyncReadEventArgs>(reader_OnEndRead);
reader.OnStateChanged +=
new EventHandler<AsyncStreamStateChangeArgs>(reader_OnStateChanged);
reader.OnError += new EventHandler<AsyncReadErrorEventArgs>(reader_OnError);
reader.BeginRead();
Here is the OnReadedBytes
event:
void reader_OnReadedBytes(object sender, AsyncReadEventArgs e)
{
int percents = e.PercentReaded; // percents of readed bytes
bool isComplete = e.IsComplete; // is read completed
long bytesReaded = e.BytesReaded; // number of readed bytes
long length = e.Length; // total length of bytes to read;
byte[] bytes = e.Result; // all readed bytes
}