8.0 Streams(2)

More things about Streams...

I'm going to talk mainly about the Asynch I/O.

Since it's a bit complicated, I'll explain codes more specifically.

In the class, first, we should define some class member variables.

private Stream inputStream;
private AsyncCallback myCallBack;
private byte[] buffer;
const int BufferSize = 256;

Then, a class constructor.

Program()
{
   inputStream = File.OpenRead(@"D:USEFORTEST.txt");
   buffer = new byte[BufferSize];
   myCallBack = new AsyncCallback(this.OnCompletedRead);
}

And now, let's go to the Main() function.

public static void Main()
{
   Program theApp = new Program();
   theApp.Run();
}

When we create a new Program theApp, we invoke the constructor of the Program class. In this step, we'll open the file that we want to read using the inputStream and create a buffer as the preparation for what we read from the file. And then, invoke the Run() function.

void Run()
{
     inputStream.BeginRead(buffer, 0, buffer.Length, myCallBack, null);
     for (long i = 0; i < 10000; i++)
     {
           if (i % 100 == 0)
           {
                 Console.WriteLine("i: {0}", i);
            }
     }
}                 

At the beginning of the Run(), the inputStream begins to read from the file to the buffer we created before. However, the program won't wait for the stream to finish the reading process and then continue the next statements. That's an inefficient way. Instead, it will start a new thread to go on(in this case, go on counting numbers). When the stream finishes reading, it will CallBack to write out the result. At this step, counting will stop for a while.

Following shows how to realize the writing out behavior. It depends on how we define the myCallBack.

void OnCompletedRead(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);
     }
}           

Finnally, the whole codes with the console output.

(just a part of the out put for it's too long)

//Begin with counting, and when it finishes the first part of reading, it stops counting and begin to show the file.

//After writing out the file, it return to count numbers again. 

Actually, this is the end of the test codes.But when I coded, I meet a small problem that confused me. That is, in the above codes, I counted from 0 to 10000, and got the expected result, however, if I use 500000 instead of 10000, we can only get the numbers from maybe 202000 to the end without smaller numbers or the file's content. Is it just because the test number is too large to show?

-----------------END & TO BE CONTINUED-----------------

原文地址:https://www.cnblogs.com/lyli/p/4483157.html