C# 异步读文件
class AsynchIOTester
{
static void Main(string[] args)
{
AsynchIOTester test = new AsynchIOTester();
test.Run();
Console.ReadKey();
}
private Stream inputStream;
private AsyncCallback myCallback;
private byte[] buffer;
const int BufferSize = 256;
public AsynchIOTester()
{
inputStream = File.OpenRead(@"C:\Users\User\Desktop\Noname1.html");
myCallback = new AsyncCallback(this.OnConpleteRead);
buffer = new byte[BufferSize];
}
void OnConpleteRead(IAsyncResult asyncResult)
{
int bytesRead = inputStream.EndRead(asyncResult);
if (bytesRead > 0)
{
string s = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine(s);
inputStream.BeginRead(buffer, 0, buffer.Length, myCallback, null);
}
}
void Run()
{
inputStream.BeginRead(buffer, 0, buffer.Length, myCallback, null);
for (long i = 0; i < 1000000; i++)
{
if (i % 1000 == 0)
{
Console.Write("i=" + i);
}
}
}
}