Synchronous Writing, Asynchronous Reading : synchronized « Thread « C# / CSharp Tutorial






using System;
using System.IO;
using System.Threading;

class MainClass
{
    static FileStream BinaryFile = new FileStream("test.dat", FileMode.Create, FileAccess.ReadWrite);
    static byte[] ByteArray = new byte[256];
    static IAsyncResult AsyncResultImplementation = null;
    static AsyncCallback ReadBytesCompleteCallback = new AsyncCallback(OnReadBytesComplete);

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

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








20.16.synchronized
20.16.1.Using synchronized methods
20.16.2.Sync Delegate
20.16.3.Shared Resource
20.16.4.Synchronous Writing, Asynchronous Reading