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 5-22 extracted from chapter
Processes, threads and synchronization
Listing 5-21< > Listing 5-23
This listing can be compiled with the command line: csc.exe /target:exe Example_5_22.cs Errors: 0 Warnings: 0
Example_5_22.cs
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
class Program {
public delegate int Deleg( int a, int b );
// Initial state of the event: false.
static AutoResetEvent ev = new AutoResetEvent( false );
static int WriteSum( int a, int b ) {
Console.WriteLine( " Thread#{0}: Sum = {1}",
Thread.CurrentThread.ManagedThreadId , a + b );
return a + b;
}
static void SumDone(IAsyncResult async) {
// Wait a second to simulate some work.
Thread.Sleep( 1000 );
Deleg proc = ( (AsyncResult) async ).AsyncDelegate as Deleg;
int sum = proc.EndInvoke( async );
Console.WriteLine( "Thread#{0}: Callback method sum = {1}",
Thread.CurrentThread.ManagedThreadId , sum );
ev.Set();
}
static void Main() {
Deleg proc = WriteSum;
// The C#2 compiler infer a delegate object of type AsyncCallback
// to reference the SumDone() method.
IAsyncResult async = proc.BeginInvoke( 10, 10, SumDone , null );
Console.WriteLine(
"Thread#{0}: BeginInvoke() called! Wait for SumDone() completion.",
Thread.CurrentThread.ManagedThreadId );
ev.WaitOne();
Console.WriteLine(
"{0}: Bye... ", Thread.CurrentThread.ManagedThreadId );
}
}
Copyright Patrick Smacchia 2006 2007
|