CHAPTER 17 PROCESSES, APPDOMAINS, AND OBJECT CONTEXTS
// A context-agile object is loaded into context zero.
class SportsCar{}
On the other hand, objects that do demand contextual allocation are termed context-bound objects,
and they must derive from the System.ContextBoundObject base class. This base class solidifies the fact
that the object in question can function appropriately only within the context in which it was created.
Given the role of .NET context, it should stand to reason that if a context-bound object were to somehow
end up in an incompatible context, bad things would be guaranteed to occur at the most inopportune
times.
In addition to deriving from System.ContextBoundObject, a context-sensitive type will also be
adorned by a special category of .NET attributes termed (not surprisingly) context attributes. All context
attributes derive from the ContextAttribute base class. Let’s see an example.
Defining a Context-Bound Object
Assume that you want to define a class (SportsCarTS) that is automatically thread safe in nature, even
though you have not hard-coded thread synchronization logic within the member implementations. To
do so, derive from ContextBoundObject and apply the [Synchronization] attribute as follows:
using System.Runtime.Remoting.Contexts;
// This context-bound type will only be loaded into a
// synchronized (hence thread-safe) context.
[Synchronization]
class SportsCarTS : ContextBoundObject
{}
Types that are attributed with the [Synchronization] attribute are loaded into a thread-safe context.
Given the special contextual needs of the SportsCarTS class type, imagine the problems that would occur
if an allocated object were moved from a synchronized context into a nonsynchronized context. The
object is suddenly no longer thread safe and, thus, becomes a candidate for massive data corruption, as
numerous threads are attempting to interact with the (now thread-volatile) reference object. To ensure
the CLR does not move SportsCarTS objects outside of a synchronized context, simply derive from
ContextBoundObject.
Inspecting an Object’s Context
Although very few of the applications you will write will need to programmatically interact with context,
here is an illustrative example. Create a new Console Application named ObjectContextApp. This
application defines one context-agile class (SportsCar) and a single context-bound type (SportsCarTS) as
follows:
using System;
using System.Runtime.Remoting.Contexts; // For Context type.
using System.Threading; // For Thread type.
// SportsCar has no special contextual
// needs and will be loaded into the
// default context of the AppDomain.
class SportsCar
{
public SportsCar()
647