
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1028
|
Chapter 18: Threading and Synchronization
The output for this code looks like this:
Calling BeginInvoke on Thread 9
Invoked Method1 on Thread 10
retVal (TimeOut): 1
Discussion
The asynchronous delegates in this recipe are created and invoked in the same fash-
ion as the asynchronous delegate in Recipe 18.4. However, instead of using the
IsCompleted property to determine whether the asynchronous delegate is finished
processing,
WaitHandle.WaitOne is used. This method blocks the thread that it is
called on either indefinitely or for a specified length of time. This method will stop
blocking the thread when it is signaled by the
ThreadPool that the thread has com-
pleted or timed out and returns a
true indicating that the asynchronous processing is
finished. If the processing is not finished before the allotted time-out value expires,
WaitOne returns false. Note that the WaitOne method that accepts no parameters will
block the calling thread indefinitely.
It is usually a better idea to include a time-out value when using the
WaitOne method, as this will prevent the calling thread from being
blocked forever if a deadlock situation occurs (in which case the
thread on which the
WaitOne method waits is never signaled) or if the
thread running the asynchronous delegate never returns, such as