Synchronous Writing, Asynchronous Reading : Asynchronous Input output : File Stream C# Source Code


Custom Search

C# Source Code » File Stream » Asynchronous Input output »

 

Synchronous Writing, Asynchronous Reading








    

//Code revised from Chapter 25 - Accessing Data Streams
//C# Bible
//by Jeff Ferguson et al. 

using System;
using System.IO;
using System.Threading;
   
class FileTestClass
{
    private static FileStream    BinaryFile = new FileStream("test.dat", FileMode.Create, FileAccess.ReadWrite);
    private static byte []       ByteArray = new byte [256];
    private static IAsyncResult  AsyncResultImplementation;
    private static AsyncCallback ReadBytesCompleteCallback= new AsyncCallback(OnReadBytesComplete);

    public static void OnReadBytesComplete(IAsyncResult AsyncResult)
    {
        int BytesRead;
        int Failures;
   
        BytesRead = BinaryFile.EndRead(AsyncResult);
        Failures = 0;
        for(int i = 0; i < 256; i++)
        {
            if(ByteArray[i] != (byte)i)
            {
                Console.WriteLine("Read test failed for byte at offset {0}.", i);
                Failures++;
            }
        }
    }
    static public void Main()
    {
        for(int i = 0; i < 256; i++)
            ByteArray[i] = (byte)i;
        BinaryFile.Write(ByteArray, 0, 256);

        BinaryFile.Seek(0, SeekOrigin.Begin);
        AsyncResultImplementation = BinaryFile.BeginRead(ByteArray, 0, 256, ReadBytesCompleteCallback, null);

        WaitHandle WaitOnReadIO = AsyncResultImplementation.AsyncWaitHandle;
        WaitOnReadIO.WaitOne();
    }    
}

           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo File Stream
» Asynchronous Input output