How to read file asynchronous with C#?

.NET provides Stream.BeginRead Method with following parameters:

buffer
The buffer to read the data into.

offset
The byte offset in buffer at which to begin writing data read from the stream.

count
The maximum number of bytes to read.

callback
An optional asynchronous callback, to be called when the read is complete.

state
A user-provided object that distinguishes this particular asynchronous read request from other requests.

Example:


FileStream fs = new FileStream(fileA, FileMode.Open);
Byte[] data = new byte[200];
long timeNow = Stopwatch.GetTimestamp();
fs.BeginRead(data, 0, data.Length, delegate(IAsyncResult ar)
{
int bytesRead = fs.EndRead(ar);
fs.Close();
// do some stuff…
}, null);
// do some stuff…





Answers and Comments


Saved Stories

Sponsored Categories