Concepts of Programming Languages

(Sean Pound) #1

616 Chapter 13 Concurrency


the IAsyncResult interface defines the IsCompleted property. While
the called thread is executing, the caller can include code it can execute in a
while loop that depends on IsCompleted. For example, we could have the
following:

IAsyncResult result = myThread.BeginInvoke(10, null, null);
while(!result.IsCompleted) {
// Do some computation
}

This is an effective way to accomplish something in the calling thread while
waiting for the called thread to complete its work. However, if the amount of
computation in the while loop is relatively small, this is an inefficient way to
use that time (because of the time required to test IsCompleted). An alterna-
tive is to give the called thread a delegate with the address of a callback method
and have it call that method when it is finished. The delegate is sent as the
second last parameter to BeginInvoke. For example, consider the following
call to BeginInvoke:

IAsyncResult result = myThread.BeginInvoke(10,
new AsyncCallback(MyMethodComplete), null);

The callback method is defined in the caller. Such methods often simply
set a Boolean variable, for example named isDone, to true. No matter how
long the called thread takes, the callback method is called only once.

13.8.2 Synchronizing Threads


There are three different ways that C# threads can be synchronized: the
Interlocked class, the Monitor class from the System.Threading
namespace, and the lock statement. Each of these mechanisms is designed
for a specific need. The Interlocked class is used when the only operations
that need to be synchronized are the incrementing and decrementing of an
integer. These operations are done atomically with the two methods of Inter-
locked, Increment and Decrement, which take a reference to an integer as
the parameter. For example, to increment a shared integer named counter in
a thread, we could use

Interlocked.Increment(ref counter);

The lock statement is used to mark a critical section of code in a thread.
The syntax of this is as follows:

lock(token) {
// The critical section
}
Free download pdf