CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 467 static (Web hosting faq)
Monday, December 31st, 2007CHAPTER 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.