Contexts

Under .NET, a class can be configured to require certain services such as synchronization, transaction, just-in-time activation, security, and so on. These configuration settings together define a runtime environment for the instances of the class to live in. This runtime environment is referred to as the context and the configuration settings are called context attributes.

A context holds one or more like-minded objects. Whenever a new object is created, the runtime examines whether the creator's context is compatible with the context attributes specified on the object. If the context is found to be compatible, the object is created in this context. Otherwise, the runtime creates a new context and places the object there. Once created, the context remains fixed and immutable until all the objects within the context are deactivated.

An application domain holds one or more contexts. When an application domain is created, the runtime creates a default context within the AppDomain. Subsequently, more contexts may get created within the domain as more objects are created. The relationship among objects, contexts, and application domains is illustrated in Figure 6.2.

Figure 6.2. Objects, contexts, and AppDomains.


Note that objects live in contexts. When we refer to an object from an AppDomain, it automatically implies an object from a context within an AppDomain. Also note that a context cannot span multiple application domains, just as an application domain cannot span multiple processes.

The .NET Framework encapsulates the context environment in a class called Context (namespace System.Runtime.Remoting.Contexts). The context that a thread is currently executing under can be obtained using a static method, Thread.CurrentContext (class Thread is defined under namespace System.Threading). The following code excerpt displays the context identifier for the current context. A context identifier is a numeric value that uniquely identifies a context within an application domain.

// Project AppDomain/ContextID

public static void Main() {
  Context cur = Thread.CurrentContext;
  Console.WriteLine("Context ID={0}", cur.ContextID);
}

When this code is executed, it outputs a value of 0, which is the context identifier for the default context. Note that the context identifier is unique only within the scope of an application domain. Two contexts from two different application domains can have the same identifier.

Now that we have a fairly good understanding of contexts and application domains, let's take a look at how objects can communicate across contexts (and application domains).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.224.197