S
Sunit Joshi
All
I'm trying to use the asynchronous method of reading a big file and
outputting it but somehow it prints out the whole file before running
the main routine.
Here's the code.
using System;
using System.IO;
using System.Threading;
using System.Text;
class AsynchFile
{
private FileStream fs;
private byte[] buffer;
const int bufSize = 256;
private AsyncCallback myCallback;
AsynchFile()
{
buffer = new byte[bufSize];
fs = new FileStream("mis_solidSymbols.log", FileMode.Open,
FileAccess.Read);
myCallback = new AsyncCallback(this.OnCompletedRead);
}
void Run()
{
fs.BeginRead(buffer, 0, buffer.Length, myCallback, null);
//Do some work while data is read
for(int i=0; i<500000; i++)
{
if(i%1000==0)
{
Console.WriteLine("** i ** : {0}", i);
//Thread.Sleep(10);
}
}
fs.Close();
}
void OnCompletedRead(IAsyncResult asyncResult)
{
int bytesRead = fs.EndRead(asyncResult);
//If we got bytes, display them and start again. Otherwise we are
done
if(bytesRead>0)
{
string s = Encoding.ASCII.GetString(buffer,0,bytesRead);
Console.WriteLine(s);
fs.BeginRead(buffer, 0, buffer.Length, myCallback, null);
}
}
public static void Main()
{
AsynchFile theApp = new AsynchFile();
theApp.Run();
}
}
It prints this line Console.WriteLine("** i ** : {0}", i); at the end.
thanks
Sunit
I'm trying to use the asynchronous method of reading a big file and
outputting it but somehow it prints out the whole file before running
the main routine.
Here's the code.
using System;
using System.IO;
using System.Threading;
using System.Text;
class AsynchFile
{
private FileStream fs;
private byte[] buffer;
const int bufSize = 256;
private AsyncCallback myCallback;
AsynchFile()
{
buffer = new byte[bufSize];
fs = new FileStream("mis_solidSymbols.log", FileMode.Open,
FileAccess.Read);
myCallback = new AsyncCallback(this.OnCompletedRead);
}
void Run()
{
fs.BeginRead(buffer, 0, buffer.Length, myCallback, null);
//Do some work while data is read
for(int i=0; i<500000; i++)
{
if(i%1000==0)
{
Console.WriteLine("** i ** : {0}", i);
//Thread.Sleep(10);
}
}
fs.Close();
}
void OnCompletedRead(IAsyncResult asyncResult)
{
int bytesRead = fs.EndRead(asyncResult);
//If we got bytes, display them and start again. Otherwise we are
done
if(bytesRead>0)
{
string s = Encoding.ASCII.GetString(buffer,0,bytesRead);
Console.WriteLine(s);
fs.BeginRead(buffer, 0, buffer.Length, myCallback, null);
}
}
public static void Main()
{
AsynchFile theApp = new AsynchFile();
theApp.Run();
}
}
It prints this line Console.WriteLine("** i ** : {0}", i); at the end.
thanks
Sunit