.NET Application Model

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 10.  .NET Framework Classes


Serialization gave you a concrete example of the flexible environment the .NET Framework provides for writing code. Now let us take a look at the model in which .NET applications run. The Win32 environment in which a program runs is called its process. This environment consists of

  • the address space in which the code and data of the program resides.

  • a set of environmental variables that is associated with the program.

  • a current drive and directory.

  • one or more threads.

Threads

A thread is the actual execution path of a program's code. One or more threads run inside of a process to allow for multiple execution paths inside of a process. For example, with multiple threads a program can update the user interface with partial results on one thread as a calculation proceeds on another thread. All threads in the same process share the process environment, and therefore all those threads can access the same process memory.

Threads are scheduled by the operating system. Processes and application domains [7] are not scheduled. Threads are given a limited timeslice in which to run so that they can share the processor with other threads. Higher priority threads will get to run more often than lower priority threads. After some time elapses, a thread will get another chance to run. When a thread is swapped back in, it resumes running from where it was swapped out.

[7] Application domains are discussed later in this chapter.

Threads maintain a context that has to be saved and restored when the operating system's scheduler switches from one thread to another. A thread's context includes the machine registers and stack that contain the state of the executing code.

The System.Threading.Thread class models an executing thread. The Thread object that represents the current executing thread can be found from the shared property Thread.CurrentThread .

Unless your code runs on a multiprocessor machine or you are trying to use time while a single processor machine waits for some event such as an I/O event, multiple threads do not result in any time saved on your computing tasks . It can, however, allow the system to seem more responsive to tasks requiring user interaction. Using too many threads can decrease performance as contention between the threads for the CPU increases .

To help you understand threads, we have a four-part Threading example that uses the Customer and Hotel assemblies from the case study to make reservations . Let us look first at Step 0.

.NET threads run as delegates defined by the ThreadStart class. The delegate returns void and takes no parameters.

 Public Delegate Sub ThreadStart() 

The NewReservation class has a public member function, MakeReservation , that will define the thread function. Since the thread function takes no parameters, any data that this function uses is assigned to fields in the NewReservation instance.

The thread delegate is created and passed as a parameter to the constructor that creates the Thread object. The Start method on the Thread object is invoked to begin the thread's execution. When we discuss the asynchronous programming model, we will show you how to pass parameters to a thread delegate. The program now has two threads, the original one that executed the code to start the thread and now the thread we just created that attempts to make a hotel reservation.

 graphics/codeexample.gif Public Class NewReservation    ...    Public Sub MakeReservation()       Console.WriteLine(_          "Thread {0} starting.", _          Thread.CurrentThread.GetHashCode())       ...       Dim result As ReservationResult = _          hotelBroker.MakeReservation(_          customerId, city, hotel, ResDate, numberDays)       ...    End Sub End Class Public Module TestThreading    ...    Public Sub Main()       Try          ...          Dim reserve1 As NewReservation = _             New NewReservation(Customers, HotelBroker)          reserve1.customerId = 1          reserve1.city = "Boston"          reserve1.hotel = "Presidential"          reserve1.sdate = "12/12/2001"          reserve1.numberDays = 3          ' create delegate for threads          Dim threadStart1 As ThreadStart = _             New ThreadStart(_             AddressOf reserve1.MakeReservation)          Dim thread1 As Thread = New Thread(threadStart1)          Console.WriteLine(_             "Thread {0} starting a new thread.", _             Thread.CurrentThread.GetHashCode())          thread1.Start()          ...    End Sub End Class 

To cause the original thread to wait until the second thread is done, the Join method on the Thread object is called. The original thread now blocks (waits) until the reservation thread is complete. The results of the reservation request are written to the console by the reservation thread.

 thread1.Join() Console.WriteLine("Done!") 
Thread Synchronization

An application can create multiple threads. Look at the code in Step 1 of the Threading example. Now multiple reservation requests are being made simultaneously .

 graphics/codeexample.gif Dim reserve1 As NewReservation = _    New NewReservation(customers, hotelBroker) ... Dim reserve2 As NewReservation = _    New NewReservation(customers, hotelBroker) ... Dim threadStart1 As ThreadStart = _    New ThreadStart(AddressOf reserve1.MakeReservation) Dim threadStart2 As ThreadStart = _    New ThreadStart(AddressOf reserve2.MakeReservation) Dim thread1 As Thread = New Thread(threadStart1) Dim thread2 As Thread = New Thread(threadStart2) ... thread1.Start() thread2.Start() thread1.Join() thread2.Join() 

The problem with our reservation system is that there is no guarantee that one thread will not interfere with the work being done with the other thread. Since threads only run for a small period before they give up the processor to another thread, they may not be finished with whatever operation they were working on when their timeslice expires .

For example, they might be in the middle of updating a data structure. If another thread tries to use the information in that data structure or to update the data structure, the results of operations will be inconsistent and incorrect, at the minimum, or a program crash (i.e., exception) will occur, at the worst (e.g., if references to obsolete structures were not yet updated).

Let us look at one of several places in the customer and reservation code where we could have a problem. Examine the code in Broker.Reserve . First a check is made of the existing bookings for a given hotel for a given date to see if there are rooms available. If the rooms are available, the booking is made.

 ... ' Check if rooms are available for all dates Dim i As Integer For i = Day To Day + numDays - 1    If numCust(i, unitid) >= unit.capacity Then       result.ReservationId = -1       result.Comment = "Room not available"       Return result    End If Next ' Reserve a room for requested dates For i = Day To Day + numDays - 1    numCust(i, unitid) += 1 Next ... 

This code can produce inconsistent results! One of the threads could be swapped out after it finds that the last room is available, but before it gets a chance to make the booking. The other thread could run, find the same available room, and make the booking. When the second thread runs again, starting from where it left off, it will also book the last room at the hotel.

To simulate this occurrence, this step of the threading example puts a Thread.Sleep call between the code that checks for room availability and the code that makes the room booking. Of course, this could happen without calling Sleep , but as is often the case with threading problems, it is not necessarily very consistent. Adding the call to Sleep just ensures that we see the bad thing happening consistently each time we run the program. The Sleep call will cause the thread to stop executing and give up the remainder of its timeslice. We then set up our program so that the two threads try to reserve the only room at a hotel for the same time. Examine the code in the Main routine that sets this up:

 hotelBroker.AddHotel(_    "Boston", "Presidential", 1, 10000D) ... Dim reserve1 As NewReservation = _    New NewReservation(customers, hotelBroker) reserve1.customerId = 1 reserve1.city = "Boston" reserve1.hotel = "Presidential" reserve1.sdate = "12/12/2001" reserve1.numberDays = 3 Dim reserve2 As NewReservation = _    New NewReservation(customers, hotelBroker) reserve2.customerId = 2 reserve2.city = "Boston" reserve2.hotel = "Presidential" reserve2.sdate = "12/13/2001" reserve2.numberDays = 1 

Running the program will give results that look something like this:

 Added Boston Presidential Hotel with one room. Thread 110 starting  new threads. Thread 111 starting. Thread 112 starting.  Reserving for Customer 1 ... on 12/12/2001 ... for 3 days   Reserving for Customer 2 ... on 12/13/2001 ... for 1 days  Thread 112 entered Broker::Reserve Thread 112 sleeping in Broker::Reserve Thread 111 entered Broker::Reserve Thread 111 sleeping in Broker::Reserve Thread 112 left Broker::Reserve  Reservation for Customer 2 has been booked  ReservationId = 1 ReservationRate = 10000 Thread 111 left Broker::Reserve  Reservation for Customer 1 has been booked  ReservationId = 2 ReservationRate = 10000 ReservationCost = 30000 Comment = OK ReservationCost = 10000 Comment = OK Done! 

Both customers get to reserve the last room on December 13! Note how Thread 112 enters the Reserve method and finds the room is available before it gets swapped out. Then Thread 111 enters Reserve and also finds the room is available before it gets swapped out. Thread 112 then books the room, and then Thread 111 does as well.

Operating systems provide means for synchronizing the operation of multiple threads or multiple processes accessing shared resources. The .NET Framework provides several mechanisms to prevent threading conflicts.

Every object in the .NET Framework can be used to provide a synchronized section of code (critical section). Only one thread at a time can execute within such a section. If one thread is already executing inside that synchronized code section, any threads that attempt to access that section will block (wait) until the executing thread leaves that code section.

Synchronization with Monitors

The System.Threading.Monitor class allows threads to synchronize on an object to avoid race conditions. Step 2 of the Threading example demonstrates the use of the Monitor class with the Me reference of the HotelBroker instance.

 graphics/codeexample.gif Public Function Reserve(ByVal res As Reservation) _  As ReservationResult    ...  Monitor.Enter(Me)  ...  Monitor.Exit(Me)  Return result End Function 

The thread that first calls the Monitor.Enter method will be allowed to execute the code of the Reserve method because it will acquire the Monitor lock based on the Me reference. Subsequent threads that try to execute this block of code will have to wait until the first thread releases the lock with Monitor.Exit . At that point they will be able to return from their call to Monitor.Enter and acquire the lock and then proceed.

A thread can call Monitor.Enter several times, but each call must be balanced by a call to Monitor.Exit . If a thread wants to try to acquire a lock, but does not want to block, it can use the Monitor.TryEnter method.

In the VB.NET language, you can use the SyncLock keyword in place of Monitor.Enter/Exit . With the SyncLock keyword, the above fragment would be

 Public Function Reserve(ByVal res as Reservation) _  As ReservationResult    ...  SyncLock Me  ...  End SyncLock  Return result End Function 

Now that we have provided synchronization, the identical case tried in Step 1 does not result in one reservation too many for the hotel. Notice how the second thread cannot enter the Reserve method until the first thread that entered has left.

 Added Boston Presidential Hotel with one room. Thread 108 starting  new threads. Thread 109 starting.  Reserving for Customer 1 ... on 12/12/2001 ... for 3 days  Thread 110 starting.  Reserving for Customer 2 ... on 12/13/2001 ... for 1 days  Thread 109 trying to enter Broker::Reserve Thread 109 entered Broker::Reserve Thread 109 sleeping in Broker::Reserve Thread 110 trying to enter Broker::Reserve Thread 109 left Broker::Reserve  Reservation for Customer 1 has been booked  ReservationId = 1 ReservationRate = 10000 ReservationCost = 30000 Comment = OK Thread 110 entered Broker::Reserve Thread 110 left Broker::Reserve  Reservation for Customer 2 could not be booked  Room not available Done! 
Notification with Monitors

A thread that has acquired a Monitor lock can wait for a signal from another thread that is synchronizing on that same object without leaving the synchronization block. The thread invokes the Monitor.Wait method and relinquishes the lock. When notified by another thread, it reacquires the synchronization lock.

A thread that has acquired a Monitor lock can send notification to another thread waiting on the same object with the Pulse or the PulseAll methods . It is important that the thread be waiting when the pulse is sent; otherwise , if the pulse is sent before the wait, the other thread will wait forever and will never see the notification. This is unlike the reset events discussed later in this chapter. If multiple threads are waiting, the Pulse method will only put one thread on the ready queue to run. The PulseAll will put all of them on the ready queue.

The pulsing thread no longer has the Monitor lock, but is not blocked from running. Since it is no longer blocked but does not have the lock, to avoid a deadlock or race condition, this thread should try to reacquire the lock (through a Monitor.Enter or Wait ) before doing any potentially damaging work.

The Pulse example illustrates the Pulse and PulseAll methods. Running the example produces the following output:

 graphics/codeexample.gif First thread: 72 started. Thread: 74 started. Thread: 75 started. Thread: 75 waiting. Thread: 74 waiting. Thread 75 sleeping. Done. Thread 75 awake. Thread: 75 exited. Thread 74 sleeping. Thread 74 awake. Thread: 74 exited. 

The class X has a field o of type Object that will be used for a synchronization lock. The class also has a method Test that will be used as a thread delegate. The method acquires the synchronization lock and then waits for a notification. When it gets the notification, it sleeps for half a second and then relinquishes the lock.

The main method creates two threads that use the X.Test as their thread delegate and share the same object to use for synchronization. It then sleeps for 2 seconds to allow the threads to issue their wait requests and relinquish their locks. It then calls PulseAll to notify both waiting threads and relinquishes its hold on the locks. Eventually, each thread will reacquire the lock, write a message to the console, and relinquish the lock for the last time.

 Class X    Public o As Object    Public Sub New(ByVal o As Object)       Me.o = o    End Sub    Public Sub Test()       Try          Dim threadId As Long = _             Thread.CurrentThread.GetHashCode()          Console.WriteLine(_             "Thread: {0} started.", threadId)          Monitor.Enter(o)          Console.WriteLine(_             "Thread: {0} waiting.", threadId)          Monitor.Wait(o)          Console.WriteLine(_             "Thread {0} sleeping.", threadId)          Thread.Sleep(500)          Console.WriteLine(_             "Thread {0} awake.", threadId)          Monitor.Exit(o)          Console.WriteLine(_             "Thread: {0} exited.", threadId)       Catch e As Exception          Dim threadId As Long = _             Thread.CurrentThread.GetHashCode()          Console.WriteLine(_             "Thread: {0} Exception: {1}", _             threadId, e.Message)          Monitor.Exit(o)       End Try    End Sub End Class Module Pulse    Public o As Object = New Object()    Sub Main()       Console.WriteLine(_          "First thread: {0} started.", _          Thread.CurrentThread.GetHashCode())       Dim a As X = New X(o)       Dim b As X = New X(o)       Dim ats As ThreadStart = _          New ThreadStart(AddressOf a.Test)       Dim bts As ThreadStart = _          New ThreadStart(AddressOf b.Test)       Dim at As Thread = New Thread(ats)       Dim bt As Thread = New Thread(bts)       at.Start()       bt.Start()       ' Sleep allows other threads to wait before Pulse       Thread.Sleep(2000)       Monitor.Enter(o)       Monitor.PulseAll(o)       'Monitor.Pulse(o);       Monitor.Exit(o)       Console.WriteLine("Done.")    End Sub End Module 

Comment out the PulseAll call and uncomment the Pulse call, and only one thread completes because the other thread is never put on the ready queue. Remove the Sleep(2000) from the main routine, and the other threads block forever because the pulse occurs before the threads get a change to call the Wait method, and hence they will never be notified.

These methods can be used to coordinate several threads' use of synchronization locks. The Thread.Sleep method causes the current thread to stop execution (block) for a given time period. Calling Thread.Suspend will cause the thread to block until Thread.Resume is called on that same thread. Threads can also block because they are waiting for another thread to finish ( Thread.Join ). This method was used in the Threading examples so that the main thread could wait until the reservation requests were completed. Threads can also block because they are waiting on a synchronization lock (critical section).

A blocked thread can be awakened by calling Thread.Interrupt on the blocked thread. The thread will receive a ThreadInterruptedException . If the thread does not catch this exception, the runtime will catch the exception and kill the thread.

If, as a last resort, you have to kill a thread outright , call the Thread.Abort method on the thread. Thread.Abort causes the ThreadAbortException to be thrown. This exception cannot be caught, but it will cause all the Finally blocks to be executed. In addition, Thread.Abort does not cause the thread to wake up from a wait.

Since Finally blocks may take a while to execute, or the thread might be waiting, aborted threads may not terminate immediately. If you need to be sure that the thread has finished, you should wait on the thread's termination using Thread.Join .

Synchronization Classes

The .NET Framework has classes that represent the standard Win32 synchronization objects. These classes all derive from the abstract WaitHandle class. This class has shared methods, WaitAll and WaitAny , that allow you to wait on a set of synchronization objects being signaled or to wait on just one of a set of synchronization objects being signaled. It also has an instance method, WaitOne , that allows you to wait for this instance to be signaled. How the object gets signaled depends on the particular type of synchronization object that is derived from WaitHandle .

A Mutex object is used for interprocess synchronization. Monitors and synchronized code sections work only within one process. An AutoResetEvent and ManualResetEvent are used to signal whether an event has occurred. An AutoResetEvent remains signaled until a waiting thread is released. A ManualResetEvent remains signaled until its state is set to unsignaled with the Reset method. Hence, many threads could be signaled by this event. Unlike Monitors , code does not have to be waiting for the signal before the pulse is set for the reset events to signal a thread.

The .NET Framework has provided classes to solve some standard threading problems. The Interlocked class methods allow atomic operations on shared values, such as increment, decrement, comparison, and exchange. ReaderWriterLock is used to allow single writer, multiple reader access to data structures. The ThreadPool class can be used to manage a pool of worker threads.

Automatic Synchronization

You can use attributes to synchronize access to instance methods and fields of a class. However, access to shared fields and methods is not synchronized in this manner. To do this, you derive the class from the class ContextBoundObject and apply the Synchronization attribute to the class. The attribute is found in the System.Runtime.Remoting.Contexts namespace.

This attribute cannot be applied to an individual method or field. ContextBoundObject and contexts are discussed in the section on contexts. The Threading example Step 3 illustrates how to do this.

 graphics/codeexample.gif <Synchronization(SynchronizationAttribute.REQUIRED)> _  Public MustInherit Class Broker ... End Class 

You can pass one of four values that are shared fields of the SynchronizationAttribute class to the SynchronizationAttribute constructor: NOT_SUPPORTED, SUPPORTED, REQUIRED, and REQUIRES_NEW. Fully understanding how these attributes work requires the discussion in our upcoming section on contexts.

NOT_SUPPORTED means that the class cannot support synchronization of its instance methods and fields, and therefore must not be created in a synchronized context. REQUIRED means that the class requires synchronization of access to its instance methods and fields. However, if a thread is already being synchronized, it can use the same synchronization lock and can live in an existing synchronization context. REQUIRES_NEW means that not only is synchronization required, but access to its instance methods and fields must be with a unique synchronization lock and context. SUPPORTED means that the class does not require synchronization of access to its instance methods and fields, and a new context does not have to be created for it.

You can also pass a Boolean flag to the constructor to indicate if reentrancy is required. If required, callouts from methods are synchronized. Otherwise, only calls into methods are synchronized.

With this attribute, there is no need for Monitor.Enter and Monitor.Exit in the Broker::Reserve method.

Just as in Step 2, this example attempts to make two reservations for the last room in a hotel. In addition, a third thread attempts to cancel a reservation. Here is the output from running this example:

 Added Boston Presidential Hotel with one room. Thread 111 launching 3 threads. CancelReservation: Thread 128 starting. Cancelling Reservation 10 Thread 128 entered CancelReservation. Thread 128 left CancelReservation. Thread 126 starting. Thread 127 starting.  Reserving for Customer 2 ... on 12/13/2001 ... for 1 days   Reserving for Customer 1 ... on 12/12/2001 ... for 3 days  Thread 127 entered Broker::Reserve Thread 127 sleeping in Broker::Reserve Thread 127 left Broker::Reserve Thread 126 entered Broker::Reserve Thread 126 left Broker::Reserve  Reservation for Customer 1 could not be booked  Room not available  Reservation for Customer 2 has been booked  ReservationId = 1 ReservationRate = 10000 ReservationCost = 10000 Comment = OK Done! 

As in the previous case, the second thread could not enter the Reserve method until the thread that entered first finished. Only one reservation is made.

What is different about using this automatic approach is that you get the synchronization in all the methods of the class, whether you need it or not. Accessing other data in the class via other methods also causes mutually exclusive blocking. This behavior may or may not be what is desired, depending on the circumstances.

Note how only one thread can be in any method of the class at a time. For example, a thread calling CancelReservation blocks other threads from calling MakeReservation . With a reservation system, this is the behavior you would want, since you do not want the MakeReservation attempt to use a data structure that might be in the middle of being modified. In some situations, however, this is not desirable and can reduce performance. This is because this approach can increase contention, which can interfere with scalability, since you are not just locking around the specific areas that need synchronizing.

The attribute approach is simpler than using critical sections. You do not have to worry about the details of getting the synchronization implemented correctly at a detailed level. On the other hand, you can get behavior that reduces interactivity and scalability. Different applications or different parts of the same application will choose the approach that makes the most sense.

Thread Isolation

An exception generated by one thread will not cause another thread to fail. The ThreadIsolation example demonstrates this.

graphics/codeexample.gif
 Class tm    Public Sub m()       Console.WriteLine(_          "Thread {0} started", _       Thread.CurrentThread.GetHashCode())       Thread.Sleep(1000)       Dim i As Integer       For i = 0 To 9          Console.WriteLine(i)       Next       Console.WriteLine(_          "Thread {0} done", _          Thread.CurrentThread.GetHashCode())    End Sub End Class Class te    Public Sub tue()       Console.WriteLine(_          "Thread {0} started", _          Thread.CurrentThread.GetHashCode())       Dim e As Exception = _       New Exception("Thread Exception")       Throw e    End Sub End Class Module ThreadIsolation    Sub Main()       Dim tt As tm = New tm()       Dim tex As te = New te()       ' create delegate for threads       Dim ts1 As ThreadStart = _          New ThreadStart(AddressOf tt.m)       Dim ts2 As ThreadStart = _          New ThreadStart(AddressOf tex.tue)       Dim thread1 As Thread = New Thread(ts1)       Dim thread2 As Thread = New Thread(ts2)       Console.WriteLine(_          "Thread {0} starting new threads.", _          Thread.CurrentThread.GetHashCode())       thread1.Start()       thread2.Start()       Console.WriteLine(_          "Thread {0} done.", _          Thread.CurrentThread.GetHashCode())    End Sub End Module 

The following output is generated. Note how the second thread can continue to write out the numbers even though the first thread has aborted from the unhandled exception. Note also how the "main" thread that spawned the other two threads can finish without causing the other threads to terminate.

 Thread 72 starting new threads. Thread 72 done. Thread 75 started Thread 74 started Unhandled Exception: System.Exception: Thread Exception    at ThreadIsolation.te.tue() in    C:\...\ThreadIsolation.vb:line 29 0 1 2 3 4 5 6 7 8 9 Thread 74 done 

The AppDomain class (discussed later in the chapter) allows you to set up a handler to catch an UnhandledException event.

Synchronization of Collections

Some lists, such as TraceListeners , are thread safe. When this collection is modified, a copy is modified and the reference is set to the copy. Most collections, like ArrayList , are not thread safe by default. Making them automatically thread safe would decrease the performance of the collection even when thread safety is not an issue.

An ArrayList has a shared Synchronized method to return a thread-safe version of the ArrayList . The IsSynchronized property allows you to test if the ArrayList you are using is the thread-safe version. The SyncRoot property can return an object that can be used to synchronize access to a collection. This allows other threads that might be using the ArrayList to be synchronized with the same object.


Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net