Archive for December, 2007

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 467 static (Web hosting faq)

Monday, December 31st, 2007

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 467 static void Main(string[] args) { Printer p = new Printer(); Thread bgroundThread = new Thread(new ThreadStart(p.PrintNumbers)); bgroundThread.IsBackground = true; bgroundThread.Start(); } Notice that this Main() method is not making a call to Console.ReadLine() to force the console to remain visible until you press the Enter key. Thus, when you run the application, it will shut down immediately because the Thread object has been configured as a background thread. Given that the Main() method triggers the creation of the primary foreground thread, as soon as the logic in Main() completes, the AppDomain unloads before the secondary thread is able to complete its work. However, if you comment out the line that sets the IsBackground property, you will find that each number prints to the console, as all foreground threads must finish their work before the AppDomain is unloaded from the hosting process. For the most part, configuring a thread to run as a background type can be helpful when the worker thread in question is performing a noncritical task that is no longer needed when the main task of the program is finished. Source Code The BackgroundThread project is included under the Chapter 14 subdirectory. The Issue of Concurrency All the multithreaded sample applications you have written over the course of this chapter have been thread-safe, given that only a single Thread object was executing the method in question. While some of your applications may be this simplistic in nature, a good deal of your multithreaded applications may contain numerous secondary threads. Given that all threads in an AppDomain have concurrent access to the shared data of the application, imagine what might happen if multiple threads were accessing the same point of data. As the thread scheduler will force threads to suspend their work at random, what if thread A is kicked out of the way before it has fully completed its work? Thread B is now reading unstable data. To illustrate the problem of concurrency, let s build another C# console application named MultiThreadedPrinting. This application will once again make use of the Printer class created previously, but this time the PrintNumbers() method will force the current thread to pause for a randomly generated amount of time: public class Printer { public void PrintNumbers() { … for (int i = 0; i < 10; i++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write(i + ", "); } Console.WriteLine(); } }
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

Web site template - CHAPTER 14 BUILDING MULTITHREADED 466 TITHREADED APPLICATIONS

Sunday, December 30th, 2007

CHAPTER 14 BUILDING MULTITHREADED 466 TITHREADED APPLICATIONS public static void Add(object data) { if (data is AddParams) { Console.WriteLine(”ID of thread in Main(): {0}”, Thread.CurrentThread.GetHashCode()); AddParams ap = (AddParams)data; Console.WriteLine(”{0} + {1} is {2}”, ap.a, ap.b, ap.a + ap.b); } } The code within Main() is straightforward. Simply use ParameterizedThreadStart rather than ThreadStart: static void Main(string[] args) { Console.WriteLine(”***** Adding with Thread objects *****”); Console.WriteLine(”ID of thread in Main(): {0}”, Thread.CurrentThread.GetHashCode()); AddParams ap = new AddParams(10, 10); Thread t = new Thread(new ParameterizedThreadStart(Add)); t.Start(ap); … } Source Code The AddWithThreads project is included under the Chapter 14 subdirectory. Foreground Threads and Background Threads Now that you have seen how to programmatically create new threads of execution using the System. Threading namespace, let s formalize the distinction between foreground threads and background threads: Foreground threads have the ability to prevent the current application from terminating. The CLR will not shut down an application (which is to say, unload the hosting AppDomain) until all foreground threads have ended. Background threads (sometimes called daemon threads) are viewed by the CLR as expendable paths of execution that can be ignored at any point in time (even if they are currently laboring over some unit of work). Thus, if all foreground threads have terminated, any and all background threads are automatically killed when the application domain unloads. It is important to note that foreground and background threads are not synonymous with primary and worker threads. By default, every thread you create via the Thread.Start() method is automatically a foreground thread. Again, this means that the AppDomain will not unload until all threads of execution have completed their units of work. In most cases, this is exactly the behavior you require. For the sake of argument, however, assume that you wish to invoke Printer.PrintNumbers() on a secondary thread that should behave as a background thread. Again, this means that the method pointed to by the Thread type (via the ThreadStart or ParameterizedThreadStart delegate) should be able to halt safely as soon as all foreground threads are done with their work. Configuring such a thread is as simple as setting the IsBackground property to true:
Please visit Domain Name Hosting services for high quality webhost to host and run your jsp applications.

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 465 (Multiple domain web hosting) Figure

Saturday, December 29th, 2007

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 465 Figure 14-7. Multithreaded applications provide results in more responsive applications. Before we move on, it is important to note that when you build multithreaded applications (which includes the use of asynchronous delegates) on single CPU machines, you do not end up with an application that runs any faster, as that is a function of a machine s CPU. When running this application using either one or two threads, the numbers are still displaying at the same pace. In reality, multithreaded applications result in more responsive applications. To the end user, it may appear that the program is faster, but this is not the case. Threads have no power to make foreach loops execute quicker, to make paper print faster, or to force numbers to be added together at rocket speed. Multithreaded applications simply allow multiple threads to share the workload. Source Code The SimpleMultiThreadApp project is included under the Chapter 14 subdirectory. Working with the ParameterizedThreadStart Delegate Recall that the ThreadStart delegate can point only to methods that return void and take no arguments. While this may fit the bill in many cases, if you wish to pass data to the method executing on the secondary thread, you will need to make use of the ParameterizedThreadStart delegate type. To illustrate, let s re-create the logic of the AsyncCallbackDelegate project created earlier in this chapter, this time making use of the ParameterizedThreadStart delegate type. To begin, create a new console application named AddWithThreads and use the System.Threading namespace. Now, given that ParameterizedThreadStart can point to any method taking a System. Object parameter, you will create a custom type containing the numbers to be added: class AddParams { public int a; public int b; public AddParams(int numb1, int numb2) { a = numb1; b = numb2; } } Next, create a static method in the Program class that will take an AddParams type and print out the summation of each value:
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

Florida web design - CHAPTER 14 BUILDING MULTITHREADED 464 TITHREADED APPLICATIONS

Friday, December 28th, 2007

CHAPTER 14 BUILDING MULTITHREADED 464 TITHREADED APPLICATIONS To begin, set a reference to the System.Windows.Forms.dll assembly and display a message within Main() using MessageBox.Show() (you ll see the point of doing so once you run the program). Here is the complete implementation of Main(): static void Main(string[] args) { Console.WriteLine(”***** The Amazing Thread App *****n”); Console.Write(”Do you want [1] or [2] threads? “); string threadCount = Console.ReadLine(); // Name the current thread. Thread primaryThread = Thread.CurrentThread; primaryThread.Name = “Primary”; // Display Thread info. Console.WriteLine(”-> {0} is executing Main()”, Thread.CurrentThread.Name); // Make worker class. Printer p = new Printer(); switch(threadCount) { case “2″: // Now make the thread. Thread backgroundThread = new Thread(new ThreadStart(p.PrintNumbers)); backgroundThread.Name = “Secondary”; backgroundThread.Start(); break; case “1″: p.PrintNumbers(); break; default: Console.WriteLine(”I don’t know what you want…you get 1 thread.”); goto case “1″; } // Do some additional work. MessageBox.Show(”I’m busy!”, “Work on main thread…”); Console.ReadLine(); } Now, if you run this program with a single thread, you will find that the final message box will not display the message until the entire sequence of numbers has printed to the console. As you are explicitly pausing for approximately two seconds after each number is printed, this will result in a less-than-stellar end user experience. However, if you select two threads, the message box displays instantly, given that a unique Thread object is responsible for printing out the numbers to the console (see Figure 14-7).
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

CHAPTER 14 (Disney web site) BUILDING MULTITHREADED APPLICATIONS 463 3.

Thursday, December 27th, 2007

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 463 3. Create a Thread object, passing the ParameterizedThreadStart/ThreadStart delegate as a constructor argument. 4. Establish any initial thread characteristics (name, priority, etc.). 5. Call the Thread.Start() method. This starts the thread at the method referenced by the delegate created in step 2 as soon as possible. As stated in step 2, you may make use of two distinct delegate types to point to the method that the secondary thread will execute. The ThreadStart delegate has been part of the System.Threading namespace since .NET 1.0, and it can point to any method that takes no arguments and returns nothing. This delegate can be helpful when the method is designed to simply run in the background without further interaction. The obvious limitation of ThreadStart is that you are unable to pass in parameters for processing. As of .NET 2.0, you are provided with the ParameterizedThreadStart delegate type, which allows a single parameter of type System.Object. Given that anything can be represented as a System.Object, you can pass in any number of parameters via a custom class or structure. Do note, however, that the ParameterizedThreadStart delegate can only point to methods that return void. Working with the ThreadStart Delegate To illustrate the process of building a multithreaded application (as well as to demonstrate the usefulness of doing so), assume you have a console application (SimpleMultiThreadApp) that allows the end user to choose whether the application will perform its duties using the single primary thread or split its workload using two separate threads of execution. Assuming you have used the System.Threading namespace via the C# using keyword, your first step is to define a type method to perform the work of the (possible) secondary thread. To keep focused on the mechanics of building multithreaded programs, this method will simply print out a sequence of numbers to the console window, pausing for approximately two seconds with each pass. Here is the full definition of the Printer class: public class Printer { public void PrintNumbers() { // Display Thread info. Console.WriteLine(”-> {0} is executing PrintNumbers()”, Thread.CurrentThread.Name); // Print out numbers. Console.Write(”Your numbers: “); for(int i = 0; i < 10; i++) { Console.Write(i + ", "); Thread.Sleep(2000); } Console.WriteLine(); } } Now, within Main(), you will first prompt the user to determine if one or two threads will be used to perform the application s work. If the user requests a single thread, you will simply invoke the PrintNumbers() method within the primary thread. However, if the user specifies two threads, you will create a ThreadStart delegate that points to PrintNumbers(), pass this delegate object into the constructor of a new Thread object, and call Start() to inform the CLR this thread is ready for processing.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

CHAPTER 14 BUILDING MULTITHREADED 462 TITHREADED APPLICATIONS (Web host forum)

Wednesday, December 26th, 2007

CHAPTER 14 BUILDING MULTITHREADED 462 TITHREADED APPLICATIONS Figure 14-6. Debugging a thread with Visual Studio 2005 The Priority Property Next, notice that the Thread type defines a property named Priority. By default, all threads have a priority level of Normal. However, you can change this at any point in the thread s lifetime using the ThreadPriority property and the related System.Threading.ThreadPriority enumeration: public enum ThreadPriority { AboveNormal, BelowNormal, Highest, Idle, Lowest, Normal, // Default value. TimeCritical } If you were to assign a thread s priority level to a value other than the default (ThreadPriority. Normal), understand that you would have little control over when the thread scheduler switches between threads. In reality, a thread s priority level offers a hint to the CLR regarding the importance of the thread s activity. Thus, a thread with the value ThreadPriority.Highest is not necessarily guaranteed to given the highest precedence. Again, if the thread scheduler is preoccupied with a given task (e.g., synchronizing an object, switching threads, or moving threads), the priority level will most likely be altered accordingly. However, all things being equal, the CLR will read these values and instruct the thread scheduler how to best allocate time slices. All things still being equal, threads with an identical thread priority should each receive the same amount of time to perform their work. In most cases, you will seldom (if ever) need to directly alter a thread s priority level. In theory, it is possible to jack up the priority level on a set of threads, thereby preventing lower-priority threads from executing at their required levels (so use caution). Source Code The ThreadStats project is included under the Chapter 14 subdirectory. Programmatically Creating Secondary Threads When you wish to programmatically create additional threads to carry on some unit of work, you will follow a very predictable process: 1. Create a type method to be the entry point for the new thread. 2. Create a new ParameterizedThreadStart (or legacy ThreadStart) delegate, passing the address of the method defined in step 1 to the constructor.
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

Michigan web site - CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 461 application

Tuesday, December 25th, 2007

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 461 application named ThreadStats. As you know, the static Thread.CurrentThread property retrieves a Thread type that represents the currently executing thread. Once you have obtained the current thread, you are able to print out various statistics: // Be sure to ‘use’ the System.Threading namespace. static void Main(string[] args) { Console.WriteLine(”***** Primary Thread stats *****n”); // Obtain and name the current thread. Thread primaryThread = Thread.CurrentThread; primaryThread.Name = “ThePrimaryThread”; // Show details of hosting AppDomain/Context. Console.WriteLine(”Name of current AppDomain: {0}”, Thread.GetDomain().FriendlyName); Console.WriteLine(”ID of current Context: {0}”, Thread.CurrentContext.ContextID); // Print out some stats about this thread. Console.WriteLine(”Thread Name: {0}”, primaryThread.Name); Console.WriteLine(”Has thread started?: {0}”, primaryThread.IsAlive); Console.WriteLine(”Priority Level: {0}”, primaryThread.Priority); Console.WriteLine(”Thread State: {0}”, primaryThread.ThreadState); Console.ReadLine(); } Figure 14-5 shows the output for the current application. The Name Property While this code is more or less self-explanatory, do notice that the Thread class supports a property called Name. If you do not set this value, Name will return an empty string. However, once you assign a friendly string moniker to a given Thread object, you can greatly simplify your debugging endeavors. If you are making use of Visual Studio 2005, you may access the Threads window during a debugging session (select Debug .Windows . Threads). As you can see from Figure 14-6, you can quickly identify the thread you wish to diagnose. Figure 14-5. Gathering thread statistics
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

CHAPTER 14 BUILDING MULTITHREADED 460 TITHREADED APPLICATIONS (Cheap web hosting)

Monday, December 24th, 2007

CHAPTER 14 BUILDING MULTITHREADED 460 TITHREADED APPLICATIONS The System.Threading.Thread Class The most primitive of all types in the System.Threading namespace is Thread. This class represents an object-oriented wrapper around a given path of execution within a particular AppDomain. This type also defines a number of methods (both static and shared) that allow you to create new threads within the current AppDomain, as well as to suspend, stop, and destroy a particular thread. Consider the list of core static members in Table 14-2. Table 14-2. Key Static Members of the Thread Type Static Member Meaning in Life CurrentContext This read-only property returns the context in which the thread is currently running. CurrentThread This read-only property returns a reference to the currently running thread. GetDomain() These methods return a reference to the current AppDomain or the ID GetDomainID() of this domain in which the current thread is running. Sleep() This method suspends the current thread for a specified time. The Thread class also supports several instance-level members, some of which are shown in Table 14-3. Table 14-3. Select Instance-Level Members of the Thread Type Instance-Level Member Meaning in Life IsAlive Returns a Boolean that indicates whether this thread has been started. IsBackground Gets or sets a value indicating whether or not this thread is a background thread (more details in just a moment). Name Allows you to establish a friendly text name of the thread. Priority Gets or sets the priority of a thread, which may be assigned a value from the ThreadPriority enumeration. ThreadState Gets the state of this thread, which may be assigned a value from the ThreadState enumeration. Abort() Instructs the CLR to terminate the thread as soon as possible. Interrupt() Interrupts (e.g., wakes ) the current thread from a suitable wait period. Join() Blocks the calling thread until the specified thread (the one on which Join() is called) exits. Resume() Resumes a thread that has been previously suspended. Start() Instructs the CLR to execute the thread ASAP. Suspend() Suspends the thread. If the thread is already suspended, a call to Suspend() has no effect. Obtaining Statistics About the Current Thread Recall that the entry point of an executable assembly (i.e., the Main() method) runs on the primary thread of execution. To illustrate the basic use of the Thread type, assume you have a new console
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

ThreadStart must match a fixed prototype. ThreadState This

Monday, December 24th, 2007

ThreadStart must match a fixed prototype. ThreadState This enum specifies the valid states a thread may take (Running, Aborted, etc.). Timer This type provides a mechanism for executing a method at specified intervals. TimerCallback This delegate type is used in conjunction with Timer types.
We recommend high quality webhost to host and run your jsp application: christian web host services.

CHAPTER 15 NEXT (Ecommerce web host) STEPS Developing a Performance

Friday, December 14th, 2007

CHAPTER 15 NEXT STEPS Developing a Performance Management Plan Now that you have learned the performance management processes and methodologies, the next step is to start developing a performance management plan for your area within your organization and then put it into motion. If you are an architect, it is time to start communicating with application business owners and defining performance criteria inside use cases. If you are a developer, it is time to start writing unit tests, running them through performance profilers, and configuring an automated and repeatable process. Once you understand the tools you have chosen and the process you have embraced, document it and encourage other developers to follow it. If you are on the QA team, it is time to push application business owners and application technical owners to define performance criteria in use cases and then evaluate the application performance against those performance criteria. If you are on the performance testing team, it is time to start performing production staging tests and capacity assessments. You need to perform trend analysis against production metrics, build forecasts against those trends, and construct a capacity plan that responds to forecasts and ensures the integrity of your business. If you are on the production support team, it is time to build a production support workflow document calling out specific people in your triage process. You need to maintain historical information and track your effectiveness at resolving production issues. Summary This chapter began by covering a variety of tools that can help make your job easier and online resources where you can find performance-related discussions. The chapter concluded by outlining the next steps each job role within an organization should take in developing a performance management plan. Whatever your role in your organization, you can effect a positive change in the performance of your applications. The key is to take the first step from conceptual knowledge to practical application. Good luck!
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.