Reading and Writing Data – C# – part 4 (Asynchronous I/O)

Asynchronous I/O

Main methods:

  • BeginRead(), BeginWrite() (from abstract class – Stream)
public class AsynchIO
{
   private Stream inputStream;

   //public delegate void AsyncCallback (IAsyncResult ar); - declared in System namespace
   private AsyncCallback myCallBack;

   private byte[] buffer;

   public readonly static int BufferSize = 256;

   public AsynchIO()
   {
      inputStream = File.OpenRead(@"C:\test\someFile.txt");
      buffer = new byte[BufferSize];
      myCallBack = new AsyncCallback(this.OnCompletedRead);
   }

   public void Run()
   {
      inputStream.BeginRead(
         buffer, // holds the result
         0, //offset
         buffer.Length, // (BufferSize)
         myCallBack, // callback delegate
         null); // local state object
      for (long i = 0; i  0)
      {
         String s = Encoding.ASCII.GetString(buffer, 0, bytesRead);
         Console.WriteLine(s);
         inputStream.BeginRead(buffer, 0, buffer.Length, myCallBack, null);
      }
   }

   public static void Main()
   {
      AsynchIO app = new AsynchIO();
      app.Run();
   }
}
Asynchronous I/O
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s