Release Lock and Restore Lock

When reading a book it's nice to be able to stop, save your place, and resume. Often a bookmark is used to keep track of the current location. Similarly, the ReaderWriter-Lock class allows a thread to release its locks and later restore them. ReleaseLock is a method on the ReaderWriterLock class that allows a thread to release all locks, regardless of the nesting depth, and save the state to a lock cookie. Once the state is stored in the lock cookie, the RestoreLock method can be used to put...

Creating and invoking

Suppose you know that at some point you need to execute one of five delegates. One way to do that would be to create a large case statement and create each of the delegates. Another alternative is to use the CreateDelegate method of the Delegate class. CreateDelegate allows for late binding. It allows a developer to determine at runtime what method is associated with a particular delegate, along with an optional target. The target is the same as the target from the previous sections in this...

Thread Pool class and Queue UserWork Item

Threadpool Queueuserworkitem Example

In chapter 8 we constructed a simplistic thread pool implementation not surprisingly the result was somewhat complex. A thread pool allows for a simple means of performing multiple tasks on different threads. The thread pool manages its threads It controls their number, lifetime, priority, and activities. The example in listing 10.1 demonstrates adding items for the ThreadPool to process using the QueueUserWorkItem method. Listing 10.1 ThreadPool example C ThreadMethod is invoked by the thread...

Example web site monitoring

When a web site stops working correctly, the time it is unavailable can often be measured in dollars. The example we'll use in this chapter is a web site monitor, a program used to ensure that a web site is in a state such that it can service user requests in a timely manner. One approach to web site monitoring is to have a predefined page that returns an indication of health. The page is retrieved at regular intervals. This page often exercises various objects or assemblies, perhaps accesses a...

Time slice or quantum

When we go see a movie in a theater, the images seem to flow from one to another in a seamless way. In reality, many separate images are presented on the screen and our brain maps them together to form a continuous image. OSs do a similar sleight of hand with threads. Multiple threads seem to execute at the same time. This is accomplished by giving each thread in the system a tiny amount of time to do its work and then switching to another one. This happens...

The Wait Handle class

The WaitHandle class figure 8.2 allows for a form of manual synchronization manual in the sense that you, the developer, need to do most of the work. The previous chapter introduced automatic synchronization. This chapter focuses on more powerful, and fundamental, constructs of synchronization. As you can see in figure 8.2 WaitHandle is an abstract base class and, because it is, instances of it cannot be created. To utilize the methods of WaitHandle, either we must use static shared methods or...

The Auto ResetEvent class

AutoResetEvent is a form of thread synchronization that alternates between a signaled state and an unsignaled one. Think of it as acting much like the toll turnstile at the subway station. To get past the turnstile someone must first deposit the correct fare. Once the fare has been deposited, only one person may enter. The turnstile switches from the state where it allows the person to enter to the state where it does not as soon as one person has entered. In this analogy, the turnstile is in a...

Controlling Windows Forms timers

Creating a Windows Forms-based timer is very easy. The toolbox in Visual Studio includes an easy-to-use Timer control. Figure 14.1 shows the location of the Windows Forms timer in the toolbox. MonthCalendar ilil HScrollBar Jj VScrclBar Using the timer control from the toolbox is the easiest way to add a timer to the form. This is basically the same as adding a timer in Visual Basic 6. Dragging and dropping the timer icon onto a form will create the first two lines of the code that follows...

Wait and Pulse

Until now our thread methods relied on Sleep to pause between executions. Sleep should not be viewed as a synchronization mechanism. Attempting to do so will likely result in race conditions and inefficient code. Suppose that you wanted to add an entry to a queue and then signal that processing should begin on that item. This can be done in a nonblocking way by using the Wait and Pulse methods. Figure 7.16 demonstrates the steps involved with using Wait and Pulse. Figure 7.16 Steps involved in...

Reader Writer lock

9.1 Acquiring a read lock from a ReaderWriterLock 161 9.2 Acquiring a writer lock from a ReaderWriterLock 166 9.3 ReleaseLock and RestoreLock 179 ReaderWriterLock is a synchronization mechanism allowing access to data. It allows multiple threads to read the data simultaneously, but only one thread at a time to update it. While a thread is updating, no other thread can read the data. The name is misleading. It may cause you to think there are two locks in reality there is a single lock that...

Making collections threadsafe using Synchronized

We've seen that the Queue class in the Collections namespace is not thread-safe. This is the general rule for collections, with the exceptions of the Hashtable and ArrayList classes. Hashtable is thread-safe for multiple readers and a single writer. Multiple threads can read from the same Hashtable safely as long as no more than one thread is updating it. This is most likely because a reader-writer lock guards the Hashtable's data. In the next chapter we'll discuss reader-writer locks. The...

Acquire release and IsLock Held

The goal of a write lock is to enable multiple threads to read shared date while restricting write access in a way that ensures data corruption does not occur. We have already covered the read lock. Multiple threads can safely read data at the same time. Only one thread can be modifying data at one time. While a thread is modifying the shared data, no other thread can access the data without the risk of data corruption. In terms of our simulated auction, a write lock allows a new bid to be...

Mutex class Wait One and Release Mutex

Suppose that you wanted to use a single text file to store the output of multiple threads. We've seen how race conditions can happen. Any time a shared resource is used, there is the chance of a race condition. Since a file might be accessed not only by multiple threads but also multiple processes, the operating system provides for various file-sharing restrictions. Listing 8.6 Using a Mutex to guard a shared text file C private string Filename private Mutex TheMutex public ClassSafeFile bool...

Freeing named data slots

There are times when we wish to stop using one variable and start using another. The FreeNamedDataSlot method of the Thread class is used to change which data slot is associated with a name. Since .NET is a nondeterministic environment, calling FreeNamedDataSlot does not actually free the object contained in the slot. Instead, it is similar to calling the Remove method of a Hashtable. Listing 11.4 shows the impact of using FreeNamedDataSlot. Listing 11.4 FreeNamedDataSlot example C public class...

The Thread Pool class

10.1 ThreadPool class and 10.4 Two unsafe methods 190 QueueUiiei-Woi-kltem 182 10.5 The use of ThreadPools in .NET 192 10.2 The RegisterWaitForSingleObject 10.6 Summary 193 method 184 10.3 Informational methods and properties 187 A thread pool is a collection of threads tasked with units of work that exist for the life of the thread pool. It allows easy distribution of work among multiple threads and is an ideal construct for dealing with multiple short-lived tasks that can be performed in...

Handling thread exceptions in Windows Forms

In an ideal world, all thread-related exceptions would be dealt with using the appropriate try catch mechanisms. To handle those cases where some execution is not handled, we can use ThreadExceptionEventHandler. This section applies to Windows Forms development only because the event handler is associated with the Application object. The following code shows how ThreadException can be used AddHandler Application.ThreadException, AddressOf Handler Thread.CurrentThread.Name Main...

Using Sleep and Interrupt

What's the difference between a web site stress-testing tool and a web site monitor The short answer is the amount of time between requests. The goals of the two products are very different. Both applications repeatedly request pages from a web server, but a stress-testing tool is designed to request as many pages as possible a web site monitor requests its pages at a much slower rate. To slow down the requesting of pages, we can use the Thread class's Sleep method. Threads go through many...

The Interrupt method

Suppose that you're tasked with making sure your company's web site is functioning correctly. Your boss calls and asks, Is the web site down In this case, you don't want to wait until the thread finishes sleeping to find out if the web site is not well. The Interrupt method on the instance of the Thread object allows one thread to wake up another. Interrupt The Interrupt method can be called on a thread that is in the Sleep-WaitJoin state. It raises a ThreadInterruptedException that causes the...

Context and context switching

There are many threads in existence in a typical system at any given point. A count of the threads from figure 1.3 yields over a hundred. Fortunately newer versions of Windows are good at dealing with multiple threads. A single processor executes one thread at a time. The thread has the processor's attention for one quantum, a time slice. After each quantum unit passes, the processor checks to see if another thread should have the processor. When the processor decides that a different thread...

The IsThread PoolThread property

In chapter 5 we saw that the Thread class supports a Name property. The Name property cannot be set on threads that are being used by ThreadPool. To determine if a given thread is part of ThreadPool, we can use the IsThreadPoolThread property of the Thread class. Listing 10.5 shows how we can determine if a thread pool is managing a thread. Listing 10.5 Inspects the IsThreadPoolThread property of the Thread class C private void buttonInspectMainThread_Click object sender, System.EventArgs e...

Wait All

Suppose that you have a large amount of work to accomplish. It would be nice to split it up among multiple threads. Since there is no guarantee that the threads will end their work at the same time, it is important to have a means to wait for all of them to finish. WaitAll is a shared static method on the WaitHandle class. It allows the caller to wait until all elements in an array of WaitHandle-derived classes become signaled. WaitAll WaitAll is a shared static method of the WaitHandle class....

Get MaxThreads and Get AvailableThreads

Suppose you wanted to know how many threads the ThreadPool class might use, and how many it was using. This can give insight into the nature of your application. The ThreadPool class does intelligent assignment of tasks to threads. If a large number of threads are being used, the tasks are likely I O bound. The GetMaxThreads method of the ThreadPool class is used to determine the largest number of threads ThreadPool will use. The GetMaxThreads method returns two out parameters. The first is the...

The Register Wait ForSingle Object method

A common use of threads is to wait for some event to occur. The ThreadPool class provides built-in support for waiting for a WaitHandle-derived object to become signaled. At the point the WaitHandle object becomes signaled, the WaitOrTimer-Callback delegate is invoked. WaitOrTimerCallback accepts two parameters. The first is an object that contains state information used by the callback to perform any needed processing. The second parameter indicates why the method is being invoked. If the...

Wait Callback

In chapter 10 we discussed the ThreadPool class in detail. The following examples show how a work item is created and added to ThreadPool for processing Private Sub WorkMethod ByVal state As Object Trace.Write Trace.WriteLine state.ToString End Sub Dim WorkItem As WaitCallback WorkItem New WaitCallback AddressOf WorkMethod ThreadPool.QueueUserWorkItem WorkItem DateTime.Now End Sub The WaitCallback delegate is how a method and a state parameter are associated with an entry in the thread pool's...

Manual ResetEvent

Suppose that you want to know if an AutoResetEvent object is signaled. One way you could do this is to call WaitOne on it, passing in zero for the wait time. If the AutoResetEvent were not signaled, it would return false. If it were signaled, it would return true. The problem is that when an AutoResetEvent is signaled and a wait is performed on it, the object automatically switches to being not signaled. This means that if one thread were inspecting the state of things it would change them by...

System TimersTimer in Windows system services

One use of a server timer is in a system service, and .NET makes it very easy to create system services. While this book is not focused on enterprise application development, we will briefly go over the steps involved in creating a system service figure 14.3 , mainly because services and threads are often closely related. When creating a project, simply select Windows Service from the list of templates. A5P.NET Web A5P.NET Web Web Control Application Service Library li I - -'-'. Choosing to...

Cooperative multitasking

Cooperative multitasking is based on the assumption that all processes in a system will share the computer fairly. Each process is expected to yield control back to the system at a frequent interval. Windows 3.x was a cooperative multitasking system. The problem with cooperative multitasking is that not all software developers followed the rules. A program that didn't return control to the system, or did so infrequently, could make the entire system unusable. That's why Windows 3.x would...

Using Thread Static variables

Unrestricted data sharing between threads is a risky thing to do. In previous chapters we've seen that synchronization objects, such as the Monitor class, can be used to restrict access to data by multiple threads. If a variable is not a communication mechanism, there generally is no reason for it to be shared among threads. One way that a variable is not shared is by declaring it local to a method. When a local variable is declared in a method, it is created on the stack of the thread that...

Acquiring a read lock from a Reader WriterLock

The read portion of the ReaderWriterLock is the means that a thread uses to indicate that it is reading the protected data. This is needed because the determination of whether a thread can write to the protected data is based on the presence of one or more threads reading it. It doesn't make much sense for a read lock to be used without a write lock. If no thread is changing the data, there isn't much need in restricting access to it, since the data must be constant in nature. Figure 9.1...