Archive for January, 2008

Figure 15-1. Compiling *.il files using ilasm.exe Figure (Free web design)

Saturday, January 12th, 2008

Figure 15-1. Compiling *.il files using ilasm.exe Figure 15-2. The result of the round-trip At this point, you can run your new application. Sure enough, rather than pumping a message to the Console window, you will now see a message box displaying your message (see Figure 15-2). CHAPTER 15 UNDERSTANDING CIL AND THE 486 THE ROLE OF DYNAMIC ASSEMBLIES Compiling CIL Code Using SharpDevelop When working with *.il files, you may wish to make use of the freely available SharpDevelop IDE (see Chapter 2). When you create a new combine (via the File .New Combine menu option), one of your choices is to create a CIL project workspace. While SharpDevelop does not have IntelliSense support for CIL projects, CIL tokens are color-coded, and you are able to compile and run your application directly within the IDE (rather than running ilasm.exe from a command prompt). Compiling CIL Code Using ILIDE# If you re truly interested in experimenting with the CIL programming language, I also recommend downloading the latest version of a free open source CIL editor named ILIDE#. This tool, like SharpDevelop, provides color-coding, ilasm.exe integration, and various related tools. Unlike SharpDevelop, the latest version of ILIDE# now supports CIL IntelliSense! You can download ILIDE# from http://ilide.aspfreeserver.com/default-en.aspx (of course, this URL is subject to change). Figure 15-3 shows ILIDE# in action.
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

Web hosting rating - CHAPTER 15 UNDERSTANDING CIL AND THE ROLE

Friday, January 11th, 2008

CHAPTER 15 UNDERSTANDING CIL AND THE ROLE OF DYNAMIC ASSEMBLIES 485 .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 8 ldstr “CIL is way cool” call valuetype [System.Windows.Forms] System.Windows.Forms.DialogResult [System.Windows.Forms] System.Windows.Forms.MessageBox::Show(string) pop ret } In effect, you have just updated the CIL code to correspond to the following C# class definition: public class Program { static void Main(string[] args) { System.Windows.Forms.MessageBox.Show(”CIL is way cool”); } } Compiling CIL Code Using ilasm.exe Assuming you have saved this modified *.il file, you can compile a new .NET assembly using the ilasm.exe (CIL compiler) utility. Perhaps surprisingly, the CIL compiler has far fewer command-line flags than the C# compiler. Table 15-1 shows the core flags of interest. Table 15-1. Common ilasm.exe Command-Line Flags Flag Meaning in Life /debug Includes debug information (such as local variable and argument names, as well as line numbers). /dll Produces a *.dll file as output. /exe Produces an *.exe file as output. This is the default setting and may be omitted. /key Compiles the assembly with a strong name using a given *.snk file. /noautoinherit Prevents class types from automatically inheriting from System.Object when a specific base class is not defined. /output Specifies the output file name and extension. If you do not make use of the /output flag, the resulting file name is the same as the name of the first source file. To compile your updated simplehelloclass.il file into a .NET *.exe, you can issue the following command within a Visual Studio 2005 command prompt: ilasm /exe HelloProgram.il Assuming things have worked successfully, you will see the report shown in Figure 15-1.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

CHAPTER 15 UNDERSTANDING CIL AND THE 484 (My web server)

Thursday, January 10th, 2008

CHAPTER 15 UNDERSTANDING CIL AND THE 484 THE ROLE OF DYNAMIC ASSEMBLIES nop ldstr “Hello CIL code!” call void [mscorlib]System.Console::WriteLine(string) nop call string [mscorlib]System.Console::ReadLine() pop ret } Interacting with CIL:Modifying an *.il File Now that you have a better understanding of how a basic CIL file is composed, let s complete our round-tripping experiment. The goal here is to update the CIL within the existing *.il file as so: Add a reference to the System.Windows.Forms.dll assembly. Load a local string within Main(). Call the System.Windows.Forms.MessageBox.Show() method using the local string variable as an argument. The first step is to add a new .assembly directive (qualified with the extern attribute) that specifies you are using System.Windows.Forms.dll. To do so, simply update the *.il file with the following logic after the external reference to mscorlib: .assembly extern System.Windows.Forms { .publickeytoken = (B7 7A 5C 56 19 34 E0 89) .ver 2:0:0:0 } Be aware that the value assigned to the .ver directive may differ depending on which version of the .NET platform you have installed on your development machine. Here, you see that System.Windows. Forms.dll version 2.0.0.0 is used and has the public key token of B77A5C561934E089. If you open the GAC (see Chapter 11) and locate your version of the System.Windows.Forms.dll assembly, you can simply copy the correct version and public key token value via the assembly s Properties page. Next, you need to alter the current implementation of the Main() method. Locate this method within the *.il file and remove the current implementation code (the .maxstack and .entrypoint directives should remain intact; I ll describe them later): .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 8 // ToDo: Write new CIL code! } Again, the goal is to push a new string onto the stack and call the MessageBox.Show() method (rather than the Console.WriteLine() method). Recall that when you specify the name of an external type, you must make use of the type s fully qualified name (in conjunction with the friendly name of the assembly). Keeping this in mind, update the Main() method as follows:
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

1 on 1 web hosting - ne() RemoveValueFromStack: pop Leave_Function: ret } The truth

Wednesday, January 9th, 2008

ne() RemoveValueFromStack: pop Leave_Function: ret } The truth of the matter is that most code labels are completely optional. The only time code labels are truly useful (and mandatory) is when you are authoring CIL code that makes use of various branching or looping constructs. Given this, you can remove these autogenerated labels altogether with no ill effect: .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 8
We recommend you use shared web hosting services, because many users agree that it is cheap, reliable and customer-satisfying webhost.

CHAPTER 14 BUILDING MULTITHREADED 476 TITHREADED APPLICATIONS (Yahoo free web hosting)

Tuesday, January 8th, 2008

CHAPTER 14 BUILDING MULTITHREADED 476 TITHREADED APPLICATIONS At this point, you may be wondering if it would be advantageous to make use of the CLRmaintained thread pool rather than explicitly creating Thread objects. Consider these major benefits of leveraging the thread pool: The thread pool manages threads efficiently by minimizing the number of threads that must be created, started, and stopped. By using the thread pool, you can focus on your business problem rather than the application s threading infrastructure. However, using manual thread management is preferred in some cases, for example: If you require foreground threads or must set the thread priority. Pooled threads are always background threads with default priority (ThreadPriority.Normal). If you require a thread with a fixed identity in order to abort it, suspend it, or discover it by name. Source Code The ThreadPoolApp application is included under the Chapter 14 subdirectory. That wraps up our examination of multithreaded programming under .NET. To be sure, the System.Threading namespace defines numerous types beyond what I had the space to cover in this chapter. Nevertheless, at this point you should have a solid foundation to build on. Summary This chapter began by examining how .NET delegate types can be configured to execute a method in an asynchronous manner. As you have seen, the BeginInvoke() and EndInvoke() methods allow you to indirectly manipulate a background thread with minimum fuss and bother. During this discussion, you were also introduced to the IAsyncResult interface and AsyncResult class type. As you learned, these types provide various ways to synchronize the calling thread and obtain possible method return values. The remainder of this chapter examined the role of the System.Threading namespace. As you learned, when an application creates additional threads of execution, the result is that the program in question is able to carry out numerous tasks at (what appears to be) the same time. You also examined several manners in which you can protect thread-sensitive blocks of code to ensure that shared resources do not become unusable units of bogus data. Last but not least, you learned that the CLR maintains an internal pool of threads for the purposes of performance and convenience.
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

CHAPTER 14 (Web server setup) BUILDING MULTITHREADED APPLICATIONS 475 Understanding

Monday, January 7th, 2008

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 475 Understanding the CLR ThreadPool The final thread-centric topic we will examine in this chapter is the CLR thread pool. When you invoke a method asynchronously using delegate types (via the BeginInvoke() method), the CLR does not literally create a brand-new thread. For purposes of efficiency, a delegate s BeginInvoke() method leverages a pool of worker threads that is maintained by the runtime. To allow you to interact with this pool of waiting threads, the System.Threading namespace provides the ThreadPool class type. If you wish to queue a method call for processing by a worker thread in the pool, you can make use of the ThreadPool.QueueUserWorkItem() method. This method has been overloaded to allow you to specify an optional System.Object for custom state data in addition to an instance of the WaitCallback delegate: public sealed class ThreadPool { … public static bool QueueUserWorkItem(WaitCallback callBack); public static bool QueueUserWorkItem(WaitCallback callBack, object state); } The WaitCallback delegate can point to any method that takes a System.Object as its sole parameter (which represents the optional state data) and returns nothing. Do note that if you do not provide a System.Object when calling QueueUserWorkItem(), the CLR automatically passes a null value. To illustrate queuing methods for use by the CLR thread pool, ponder the following program, which makes use of the Printer type once again. In this case, however, you are not manually creating an array of Thread types; rather, you are assigning members of the pool to the PrintNumbers() method: class Program { static void Main(string[] args) { Console.WriteLine(”Main thread started. ThreadID = {0}”, Thread.CurrentThread.GetHashCode()); Printer p = new Printer(); WaitCallback workItem = new WaitCallback(PrintTheNumbers); // Queue the method 10 times for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(workItem, p); } Console.WriteLine("All tasks queued"); Console.ReadLine(); } static void PrintTheNumbers(object state) { Printer task = (Printer)state; task.PrintNumbers(); } }
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 BUILDING MULTITHREADED 474 TITHREADED (Hp web site) APPLICATIONS

Sunday, January 6th, 2008

CHAPTER 14 BUILDING MULTITHREADED 474 TITHREADED APPLICATIONS Figure 14-11. Timers at work The next step is to configure an instance of the TimerCallback delegate and pass it into the Timer object. In addition to configuring a TimerCallback delegate, the Timer constructor allows you to specify the optional parameter information to pass into the delegate target (defined as a System.Object), the interval to poll the method, and the amount of time to wait (in milliseconds) before making the first call, for example: static void Main(string[] args) { Console.WriteLine(”***** Working with Timer type *****n”); // Create the delegate for the Timer type. TimerCallback timeCB = new TimerCallback(PrintTime); // Establish timer settings. Timer t = new Timer( timeCB, // The TimerCallback delegate type. “Hi”, // Any info to pass into the called method (null for no info). 0, // Amount of time to wait before starting. 1000); // Interval of time between calls (in milliseconds). Console.WriteLine(”Hit key to terminate…”); Console.ReadLine(); } In this case, the PrintTime() method will be called roughly every second and will pass in no additional information to said method. If you did wish to send in some information for use by the delegate target, simply substitute the null value of the second constructor parameter with the appropriate information. For example, ponder the following updates: static void PrintTime(object state) { Console.WriteLine(”Time is: {0}, Param is: {1}”, DateTime.Now.ToLongTimeString(), state.ToString()); } Figure 14-11 shows the output. Source Code The TimerApp application is included under the Chapter 14 subdirectory.
If you are in need for chaep and reliable webhost to host your website, our recommendation is http web server services.

Cool web site - CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 473 context.

Saturday, January 5th, 2008

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 473 context. As you may recall from Chapter 13, objects that should not be removed from a contextual boundary should derive from ContextBoundObject. Therefore, if you wish to make the Printer class type thread-safe (without explicitly writing thread-safe code within the class members), you could update the definition as so: using System.Runtime.Remoting.Contexts; … // All methods of Printer are now thread-safe! [Synchronization] public class Printer : ContextBoundObject { public void PrintNumbers() { … } } In some ways, this approach can be seen as the lazy way to write thread-safe code, given that you are not required to dive into the details about which aspects of the type are truly manipulating thread-sensitive data. The major downfall of this approach, however, is that even if a given method is not making use of thread-sensitive data, the CLR will still lock invocations to the method. Obviously, this could degrade the overall functionality of the type, so use this technique with care. At this point, you have seen a number of ways you are able to provide synchronized access to shared blocks of data. To be sure, additional types are available under the System.Threading namespace, which I will encourage you to explore at your leisure. To wrap up our examination of thread programming, allow me to introduce three additional types: TimerCallback, Timer, and ThreadPool. Programming with Timer Callbacks Many applications have the need to call a specific method during regular intervals of time. For example, you may have an application that needs to display the current time on a status bar via a given helper function. As another example, you may wish to have your application call a helper function every so often to perform noncritical background tasks such as checking for new e-mail messages. For situations such as these, you can use the System.Threading.Timer type in conjunction with a related delegate named TimerCallback. To illustrate, assume you have a console application that will print the current time every second until the user presses a key to terminate the application. The first obvious step is to write the method that will be called by the Timer type: class TimePrinter { static void PrintTime(object state) { Console.WriteLine(”Time is: {0}”, DateTime.Now.ToLongTimeString()); } } Notice how this method has a single parameter of type System.Object and returns void. This is not optional, given that the TimerCallback delegate can only call methods that match this signature. The value passed into the target of your TimerCallback delegate can be any bit of information whatsoever (in the case of the e-mail example, this parameter might represent the name of the Microsoft Exchange server to interact with during the process). Also note that given that this parameter is indeed a System.Object, you are able to pass in multiple arguments using a System.Array or custom class/structure.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

CHAPTER 14 BUILDING MULTITHREADED 472 TITHREADED APPLICATIONS (Virtual web hosting)

Friday, January 4th, 2008

CHAPTER 14 BUILDING MULTITHREADED 472 TITHREADED APPLICATIONS Table 14-4. Members of the System.Threading.Interlocked Type Member Meaning in Life CompareExchange() Safely tests two values for equality and, if equal, changes one of the values with a third Decrement() Safely decrements a value by 1 Exchange() Safely swaps two values Increment() Safely increments a value by 1 Although it might not seem like it from the onset, the process of atomically altering a single value is quite common in a multithreaded environment. Assume you have a method named AddOne() that increments an integer member variable named intVal. Rather than writing synchronization code such as the following: public void AddOne() { lock(this) { intVal++; } } you can simplify your code via the static Interlocked.Increment() method. Simply pass in the variable to increment by reference. Do note that the Increment() method not only adjusts the value of the incoming parameter, but also returns the new value: public void AddOne() { int newVal = Interlocked.Increment(ref intVal); } In addition to Increment() and Decrement(), the Interlocked type allows you to atomically assign numerical and object data. For example, if you wish to assign the value of a member variable to the value 83, you can avoid the need to use an explicit lock statement (or explicit Monitor logic) and make use of the Interlocked.Exchange() method: public void SafeAssignment() { Interlocked.Exchange(ref myInt, 83); } Finally, if you wish to test two values for equality to change the point of comparison in a threadsafe manner, you are able to leverage the Interlocked.CompareExchange() method as follows: public void CompareAndExchange() { // If the value of i is currently 83, change i to 99. Interlocked.CompareExchange(ref i, 99, 83); } Synchronization Using the [Synchronization] Attribute The final synchronization primitive examined here is the [Synchronization] attribute, which is amember of the System.Runtime.Remoting.Contexts namespace. In essence, this class-level attribute effectively locks down all instance member code of the object for thread safety. When the CLR allocates objects attributed with [Synchronization], it will place the object within a synchronized
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 471 Source (Web site templates)

Thursday, January 3rd, 2008

CHAPTER 14 BUILDING MULTITHREADED APPLICATIONS 471 Source Code The MultiThreadedPrinting application is included under the Chapter 14 subdirectory. Synchronization Using the System.Threading.Monitor Type The C# lock statement is really just a shorthand notation for working with the System.Threading.Monitor class type. Once processed by the C# compiler, a lock scope actually resolves to the following (which you can verify using ildasm.exe): public void PrintNumbers() { Monitor.Enter(this); try { // 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++) { Random r = new Random(); Thread.Sleep(1000 * r.Next(5)); Console.Write(i + ", "); } Console.WriteLine(); } finally { Monitor.Exit(this); } } First, notice that the Monitor.Enter() method is the ultimate recipient of the thread token you specified as the argument to the lock keyword. Next, all code within a lock scope is wrapped within a try block. The corresponding finally clause ensures that the thread token is released (via the Monitor.Exit() method), regardless of any possible runtime exception. If you were to modify the MultiThreadSharedData program to make direct use of the Monitor type (as just shown), you will find the output is identical. Now, given that the lock keyword seems to require less code than making explicit use of the System.Threading.Monitor type, you may wonder about the benefits of using the Monitor type directly. The short answer is control. If you make use of the Monitor type, you are able to instruct the active thread to wait for some duration of time (via the Wait() method), inform waiting threads when the current thread is completed (via the Pulse() and PulseAll() methods), and so on. As you would expect, in a great number of cases, the C# lock keyword will fit the bill. However, if you are interested in checking out additional members of the Monitor class, consult the .NET Framework 2.0 SDK documentation. Synchronization Using the System.Threading.Interlocked Type Although it always is hard to believe until you look at the underlying CIL code, assignments and simple arithmetic operations are not atomic. For this reason, the System.Threading namespace provides a type that allows you to operate on a single point of data atomically with less overhead than with the Monitor type. The Interlocked class type defines the static members shown in Table 14-4.
From our experience, we can recommend PHP Web Hosting services, if you need affordable webhost to host and run your web application.