Concepts of Programming Languages

(Sean Pound) #1

614 Chapter 13 Concurrency


13.8.1 Basic Thread Operations


Rather than just methods named run, as in Java, any C# method can run in its
own thread. When C# threads are created, they are associated with an instance
of a predefined delegate, ThreadStart. When execution of a thread is started,
its delegate has the address of the method it is supposed to run. So, execution
of a thread is controlled through its associated delegate.
A C# thread is created by creating a Thread object. The Thread construc-
tor must be sent an instantiation of ThreadStart, to which must be sent the
name of the method that is to run in the thread. For example, we might have

public void MyRun1() {... }

...
Thread myThread = new Thread(new ThreadStart(MyRun1));


In this example, we create a thread named myThread, whose delegate points to
the method MyRun1. So, when the thread begins execution it calls the method
whose address is in its delegate. In this example, myThread is the delegate and
MyRun1 is the method.
As with Java, in C#, there are two categories of threads: actors and servers.
Actor threads are not called specifically; rather, they are started. Also, the meth-
ods that they execute do not take parameters or return values. As with Java,
creating a thread does not start its concurrent execution. For actor threads,
execution must be requested through a method of the Thread class, in this
case named Start, as in

myThread.Start();

As in Java, a thread can be made to wait for another thread to finish its
execution before continuing, using the similarly named method Join. For
example, suppose thread A has the following call:

B.Join();

Thread A will be blocked until thread B exits.
The Join method can take an int parameter, which specifies a time limit
in milliseconds that the caller will wait for the thread to finish.
A thread can be suspended for a specified amount of time with Sleep,
which is a public static method of Thread. The parameter to Sleep is an
integer number of milliseconds. Unlike its Java relative, C#’s Sleep does not
raise any exceptions, so it need not be called in a try block.
A thread can be terminated with the Abort method, although it does not
literally kill the thread. Instead, it throws ThreadAbortException, which the
thread can catch. When the thread catches this exception, it usually deallocates
any resources it allocated, and then ends (by getting to the end of its code).
A server thread runs only when called through its delegate. These threads
are called servers because they provide some service when it is requested. Server
Free download pdf