Application Domains


Application Domains Versus Processes

Chapter 4 briefly introduced the concept of an application domain . Traditionally, operating systems have allowed multiple processes to apparently execute simultaneously in memory. [2] An operating system monitors each process and isolates the address space of each application, thereby preventing a process from accessing any other process's memory. If a process does attempt to access memory outside of its address space, then the operating system will terminate the erroneous process to safeguard the integrity of the other processes, including the operating system itself. This idea of process isolation is fundamental to any modern operating system. Unfortunately, processes often require a large amount of system resources to create, monitor, and terminate; this is unfortunate when a number of short-lived processes are sometimes required to perform a task.

[2] Of course, on a single-processor machine, really only one process can execute at any time. With the use of time slicing and other techniques, however, one can create the illusion of the simultaneous execution of multiple processes.

Application domains provide an alternative to processes in the Common Language Runtime. An application domain is similar to the concept of a process, in that each application domain remains protected from other application domains reading or writing directly into it. An application domain is much less expensive to create than a separate process, however. Application domains also share one other useful trait: They are the smallest units of an executing .NET program that can be released (unloaded) from memory. Clearly, if a long-lived process must load and use a large number of external binary files, such as assemblies, it needs some means to unload these files when they are no longer needed; otherwise , it will eventually exhaust the supply of available memory.

Use of Application Domains

As an example of the use of application domains, consider a server process, such as a Web server. Web servers should have a long lifetime; generally they should start when an operating system loads and stop only when the operating system shuts down. Web servers often need to run many external scripts and programs created by developers to satisfy the requests they receive from external clients , such as browsers. Naturally, the developers of the Web servers want the execution of these external programs to be both fast and reliable. "Fast" would require that a server not create large numbers of short-lived processes to generate the needed data; "reliable" means that a server requires memory isolation from the external programs. In the past, processes such as Web servers have often sacrificed reliability for performance and allowed external programs to execute with their own address spaces. As a consequence, Web servers have tended to terminate unexpectedly. This is exactly the situation addressed by application domains.

In general, application domains are of greatest importance to developers of long-lived servers and not necessarily of interest to developers of other types of applications. For this reason, full coverage of application domains is really beyond the scope of an introductory text such as this book. For completeness, a small amount of coverage is provided here.

Example: Retrieving Current Application Domain Information

The program in Listing 5.10 offers a simple example of how to retrieve information about the current application domain from within a program. Whenever the CLR starts a program, it creates a default application domain, which is, not surprisingly, referred to as the default domain. Listing 5.10 shows how many of the concepts that are associated with a process are also relevant to an application domain, such as the application's base directory and search path .

Listing 5.10 Retrieving information about the current application domain
 using System; public class Start {   public static int Main()   {     AppDomain d = AppDomain.CurrentDomain;     Console.WriteLine("Friendly name: {0}",                       d.FriendlyName);     Console.WriteLine("Base Directory: {0}",                       d.BaseDirectory);     Console.WriteLine("Relative Search Path: {0}",                       d.RelativeSearchPath);     return 0;   } } 

Listing 5.10 generates the following output:

 Friendly name: AppDomainInfo.exe  Base Directory: C:\Project7\Demos\AppDomainInfo\ Relative Search Path: 

Example: Creating and Manipulating Application Domains

The next example shows how a developer can create and manipulate an application domain. Listing 5.11 creates a second application domain, giving it the friendly name of MyDomain . When creating an application domain, you can readily change its security and configuration settings. Here, the base directory for the application domain is changed to cause the application domain to initially look in this directory for assemblies it needs to load. The MyDomain application domain also has another search directory added to its path. Finally, both the original and the new application domains are instructed to execute the program in Listing 5.10, which displays information about the current application domain.

Listing 5.11 Creating and manipulating application domains
 using System; using System.Security.Policy; public class Start {   public static int Main()   {     AppDomain c = AppDomain.CurrentDomain;     AppDomainSetup s = new AppDomainSetup();     // using a 'verbatim' string (prefixed by '@') allows us     // to avoid doubling backslashes.     s.ApplicationBase = @"C:\Project7\Demos";     s.PrivateBinPath = @"C:\Windows";     AppDomain d = AppDomain.CreateDomain("MyDomain",                                          null, s);     Console.WriteLine("Starting App Domain c");     c.ExecuteAssembly("AppDomainInfo.exe");     Console.WriteLine("Starting App Domain d");     d.ExecuteAssembly("AppDomainInfo.exe");     return 0;   } } 

As expected, the output shows the differences in the configuration settings that have been applied to the two application domains:

 Starting App Domain c  Friendly name: AppDomain.exe Base Directory: C:\Project7\Demos\AppDomainExecute\ Relative Search Path: Starting App Domain d Friendly name: MyDomain Base Directory: C:\Project7\Demos Relative Search Path: C:\Windows 

Example: Loading Assemblies into Application Domains

The final application domain example shows how developers can load individual assemblies into different application domains, then create objects in those domains and call methods on the objects. In Listing 5.12, a helper function, PrintAssemblies , is used to display the assemblies loaded with an application domain.

Listing 5.12 Loading an assembly into an application domain
 using System; using System.Reflection; using System.Runtime.Remoting; using System.Threading; public class AppDomainSample {   private static void PrintAssemblies(AppDomain ad)   {     Assembly[] aa = ad.GetAssemblies();     foreach(Assembly a in  aa)       Console.WriteLine(a);   }   public static int Main(String[] args)   {     AppDomain ad1 = AppDomain.CreateDomain("Domain1");     AppDomain ad2 = AppDomain.CreateDomain("Domain2");     ad1.Load("first");     ad2.Load("second");     PrintAssemblies(ad1);     PrintAssemblies(ad2);     ObjectHandle oh1 = ad1.CreateInstance(                             "first", "ObjectType1");     ObjectHandle oh2 = ad2.CreateInstance(                             "second", "ObjectType2");     Object o1 = (Object) oh1.Unwrap();     Object o2 = (Object) oh2.Unwrap();     Console.WriteLine(o1);     Console.WriteLine(o2);     AppDomain.Unload(ad1);     AppDomain.Unload(ad2);     Console.WriteLine(       "Application Domains unloaded before process ends");     return 0;   } } 

Main first creates two application domains: ad1 and ad2 . Next, it loads a different assembly into each domain: first.dll and second.dll . Each assembly contains the definition of an object type that inherits directly from MarshalByRefObject : ObjectType1 in first.dll and ObjectType2 in second.dll . The program then displays the assemblies in each application domain, showing that mscorlib is available to both and that each assembly contains one other assembly, either first.dll or second.dll .

Next, the program creates objects of each type in the different application domains. Because the objects are created in different application domains than the application domain that called CreateInstance , the program returns ObjectHandle s. The ObjectHandle class allows a handle to an object to be passed between different application domains without requiring that its metadata be passed with it. When an ObjectHandle is unwrapped in an application domain, its metadata is introduced into that application domain only ”not in those application domains through which it has merely passed. After the objects are unwrapped, they are converted to strings and written to the console. The implementation of the ToString method that is called will write out the type of the object and its application domain, as shown in the program's output.

The application domains are unloaded before a message is written to the console. Finally, the program terminates.

The following output from cordbg shows the sequence of application domain creation and exiting, along with the program's output. The output has been abbreviated for space reasons.

 Microsoft (R) Common Language Runtime Test Debugger Shell  Version 1.0.3705.0 Copyright (C) Microsoft Corporation 1998-2001. All rights reserved. (cordbg) Process 1472/0x5c0 created. Appdomain #1, DefaultDomain -- Created Assembly 0x00097024, c:\windows\...\mscorlib.dll -- Loaded   in appdomain #1, DefaultDomain ... Appdomain #2, Domain2 -- Created ... Appdomain #3, Domain3 -- Created ... Assembly 0x00109904, c:\project7\...\first.dll -- Loaded   in appdomain #2, Domain1 ... Assembly 0x0010d824, c:\...\second.dll -- Loaded   in appdomain #3, Domain2 ... =====AppDomains.exe===== mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 AppDomains, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null first, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null second, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null =====Domain1===== mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 first, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null =====Domain2===== mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 second, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null ... ObjectType1 in Domain1 ObjectType2 in Domain2 ... Appdomain #2, Domain1 -- Exited ... Appdomain #3, Domain2 -- Exited Application Domains unloaded before process ends Unloaded class: AppDomainSample ... Assembly 0x00097024, c:\...\mscorlib.dll -- Unloaded Appdomain #1, AppDomains.exe -- Exited [thread 0x7bc] Thread exited. Process exited. (cordbg) 


Programming in the .NET Environment
Programming in the .NET Environment
ISBN: 0201770180
EAN: 2147483647
Year: 2002
Pages: 146

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