Home > Development > Heavy handed synchronisation with ContextBoundObjects and the Synchronization Attribute

Heavy handed synchronisation with ContextBoundObjects and the Synchronization Attribute


Most people are aware of the lock keyword or Monitor Class in .NET, but most are not awared of the Synchronization attribute and the ContextBoundObject base class.
If you make you class inherit from ContextBoundObject .NET will automatically synchronize all method calls made on that class so you do not need to wrap access to the object inside a lock it does it for you automagically.Well it does this by actually creating a proxy around your object. Method calls are actually intercepted which makes it lok like its magic:)

The Syncronization attribute is a form of declarative locking.

There is a cost however it is about 50 times slower than using a lock.

Here the code.

using System;
using System.Runtime.Remoting.Contexts;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;
using System.Runtime.Remoting;

namespace TPLTasks
{

    [Synchronization]
    public class Counter : ContextBoundObject
    {
        public int Value { get; set; }

        public void Increment()
        {
            Value++;
        }
    }

    class Program
    {
        static void Main()
        {

            Counter c = new Counter();
            Task[] tasks = new Task[10];

            for (int i = 0; i <= tasks.Length - 1; i++)
            {
                tasks[i] = Task.Factory.StartNew(
                    () =>
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            c.Increment();
                        }
                    }
                    );
            }

            Task.WaitAll(tasks);
            Console.WriteLine(c.Value);

            Console.WriteLine("Press any key to quit..");
            Console.ReadKey();
        }


    }
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: