Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press
Buy directly from Paradoxal Press at $33.99 (Save 43%)
Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA
|
Listing 17-4 extracted from chapter Input/Output and streams
Listing 17-3< > Listing 17-5
This listing can be compiled with the command line: csc.exe /target:exe Example_17_4.cs Errors: 0 Warnings: 0
Example_17_4.cs
using System;
using System.IO;
using System.Threading;
public class Program {
class FileStatus {
public byte [] Buffer;
public FileStream Fs;
public int Id;
}
// Size of files : almost 10 MB.
static readonly int NBytesPerFile = 10000000;
static readonly int NRead = 5;
static string FileName = "blob.bin";
// Create a file of NBytesPerFile bytes.
static void CreateBlobFile() {
byte [] blob = new byte[ NBytesPerFile ];
FileStream fs = new FileStream(
FileName,
FileMode.Create,FileAccess.Write,FileShare.None,
4096, false);
fs.Write( blob, 0, NBytesPerFile );
fs.Flush();
fs.Close();
}
public static void Main() {
CreateBlobFile();
for(int i = 0 ; i< NRead; i++ ) {
FileStream fs = new FileStream(
FileName,
FileMode.Open,FileAccess.Read,FileShare.Read,
// Size of the internal buffer.
4096,
true);
// Initialize data for the callback procedure.
FileStatus status = new FileStatus();
status.Id = i;
status.Fs = fs;
status.Buffer = new Byte[ NBytesPerFile ];
Console.WriteLine( "Thread #{0}: Trigger asynchronous read #{1}",
Thread.CurrentThread.ManagedThreadId ,i);
// Trigger asynchronous read.
fs.BeginRead( status.Buffer, 0, NBytesPerFile ,
new AsyncCallback(CallbackOnReadDone), status);
}
// To keep the example simple, we don't implement any
// synchronization mecanism to wait for the end of reads
// done by background threads.
Thread.Sleep(10000);
}
// The callback method which works with read data.
static void CallbackOnReadDone( IAsyncResult asyncResult ) {
// Fetch read data.
FileStatus status = asyncResult.AsyncState as FileStatus;
byte[] data = status.Buffer;
FileStream fs = status.Fs;
// Close the stream used to read data.
int nBytesRead = fs.EndRead( asyncResult );
fs.Close();
Console.WriteLine( "Thread #{0}: Begin work on data #{1}",
Thread.CurrentThread.ManagedThreadId ,status.Id);
// Simulate working on the data for one second.
Thread.Sleep(1000);
Console.WriteLine( "Thread #{0}: End work on data #{1}",
Thread.CurrentThread.ManagedThreadId ,status.Id);
}
}
Copyright Patrick Smacchia 2006 2007
|