Team LiB
Previous Section Next Section

Application Domains

Application domains ( AppDomains ) allow you to have one Win32 process that can be divided into separate areas of execution that are protected from each other. Suppose that you have a task that needs to be done, but you want to make sure that if that task fails and throws an unhandled exception, the entire process does not shut down. This is exactly what application domains do for you. They allow you to create separate execution contexts inside the same Win32 process.

The downside to using application domains is that you must use Remoting to communicate among the domains. The fact that you are using Remoting isn't bad; it's the cost of marshaling data and traversing the domains via the CrossAppDomainSink that impacts performance. You could make the performance even worse if you were to use full-blown Remoting and the TCP or HTTP channels.

An interesting fact about application domains is how threads are used. A single thread does not belong to a single application domain. Instead, threads can cross to and from application domains on demand. So, if you were to debug the following example, you would see the call to the remoted object occur on the same thread that handles that call. Another interesting fact is that the only way you can unload an assembly in a .NET project is to use application domains.

There are numerous overloads that allow you to provide evidence and setup information for the domain as well. The evidence sets the security policy for the domain. The setup information allows you to configure the configuration file information and the application base path.

The following example demonstrates how to create an AppDomain.

Code Example: How to Create an AppDomain
Start example

using System;
using System.Runtime.Remoting;

namespace Client.Chapter_9___Exception Handling_and_Application Domains
{
      class MyServer
      {
             [MTAThread]
            static void Main(string[] args)
            {
           //Creates AppDomain
            AppDomain Domain2 = AppDomain.CreateDomain("AppDomainB");
                   RemoteObj MyRemoteObj =
                      (RemoteObj)Domain2.CreateInstanceAndUnwrap
                                 ("Server", "Server.RemoteObj");
                   MyRemoteObj.Test();
                   Console.WriteLine("Finshed");
            }
      }
      public class RemoteObj: MarshalByRefObject
      {
            public RemoteObj()
            {
                  Console.WriteLine("CTOR Called");
            }
            public void Test()
            {
                  Console.WriteLine("RemObj Test Method Called");
            }
      }
}
End example

Team LiB
Previous Section Next Section