Synchronization Domains
by Richard Grimes

Listing One
class Base : ContextBoundObject
{
   // Write the class name 100 times on the console
   public void Run(object o)
   {
      string str = GetType().ToString();
      for (int i = 0; i < 100; i++)
      {
         Console.Write(str);
         Thread.Sleep(20);
      }
      Console.WriteLine();
   }
}


Listing Two
class A : Base {}
class B : Base {}

class App
{
   static void Main()
   {
      App app = new App();
      app.Start();
      // Keep main thread alive
      Console.ReadLine();
   }
   void Start()
   {
      A a = new A();
      B b = new B();
      ThreadPool.QueueUserWorkItem(new WaitCallback(a.Run));
      ThreadPool.QueueUserWorkItem(new WaitCallback(b.Run));
   }
}


Listing Three
[Synchronization(SynchronizationAttribute.REQUIRED)]
class Base : ContextBoundObject
{
   // rest of the code is the same as before
}
class A : Base
{
   // Create a B object in the same context as the A object
   public B CreateB()
   {
      return new B();
   }
}
class B : Base {}
class App
{
   static void Main()
   {
      App app = new App();
      app.Start();
      // Keep main thread alive
      Console.ReadLine();
   }
   void Start()
   {
      A a = new A();
      B b = a.CreateB();
      ThreadPool.QueueUserWorkItem(new WaitCallback(a.Run));
      ThreadPool.QueueUserWorkItem(new WaitCallback(b.Run));
   }
}






