Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Exemple d’écriture Asynchrone et lecture Synchone

fichier, lecture-fichier, écriture-fichier, FileStream, BinaryWriter, BinaryReader, copier-fichier, attribut-Fichier, sérialisation
{filelink=15733}

//C# Bible
//Par Jeff Ferguson et al. 
 
using System;
using System.IO;
using System.Threading;
 
class ExempleAsynchSynch
{
    private static FileStream    BinaryFile = new FileStream("test.dat", FileMode.Create, FileAccess.ReadWrite);
    private static byte []       ByteArray = new byte [256];
    private static IAsyncResult  AsyncReadResultImplementation = null;
    private static IAsyncResult  AsyncWriteResultImplementation;
    private static AsyncCallback ReadBytesCompleteCallback = new AsyncCallback(OnReadBytesComplete);
    private static AsyncCallback WriteBytesCompleteCallback = new AsyncCallback(OnWriteBytesComplete);
 
    public static void OnReadBytesComplete(IAsyncResult AsyncResult)
    {
        int BytesRead;
        int Failures;
 
        BytesRead = BinaryFile.EndRead(AsyncResult);
        Console.WriteLine("Bytes read........: {0}", BytesRead);
        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++;
            }
        }
        Console.WriteLine("Read test failures: {0}", Failures);
    }
    public static void OnWriteBytesComplete(IAsyncResult AsyncResult)
    {
        BinaryFile.EndWrite(AsyncResult);
    }
    static public void Main()
    {
        for(int i = 0; i < 256; i++)
            ByteArray[i] = (byte)i;
        AsyncWriteResultImplementation = BinaryFile.BeginWrite(ByteArray, 0, 256, WriteBytesCompleteCallback, null);
 
        WaitHandle WaitOnWriteIO = AsyncWriteResultImplementation.AsyncWaitHandle;
        WaitOnWriteIO.WaitOne();
 
        BinaryFile.Seek(0, SeekOrigin.Begin);
        AsyncReadResultImplementation = BinaryFile.BeginRead(ByteArray, 0, 256, ReadBytesCompleteCallback, null);
 
        WaitHandle WaitOnReadIO = AsyncReadResultImplementation.AsyncWaitHandle;
        WaitOnReadIO.WaitOne();
    }
}

No comments yet.

Leave a Comment