3

I created a class for thread synchronization, that I want to apply to methods, classes, properties etc without going through and inserting my code into every function, class etc. This is an example of the current implementation I have to do:

public class NotWhatIWantExample
{
    LockingClass locker;
    public int function()
    {
        locker.EnterWriteBlock();
        if (condition)
        {
            locker.LeaveWriteBlock();
            return 0;
        }
        locker.LeaveWriteBlock();
        return 1;
    }
}

Next is two examples of what I want to do if possible

Example 2:

// [LockingClassAttribute(LockingClassAttribute.WriteBlock)] 
// Not Declared But Added Since Attribute Is Applied On A Method
public class WhatIWantExample
{
    //LockingClass locker; Included In The Attribute

    [LockingClassAttribute(LockingClassAttribute.WriteBlock)]public int function()
    {
        if (condition)
            return 0;
    }
}

Example 3:

[LockingClassAttribute(LockingClassAttribute.ReadWriteBlock)]
public class WhatIWantExample
{
    //LockingClass locker; Included In The Attribute

    //Function Would Override LockingClassAttribute.ReadWriteBlock
    [LockingClassAttribute(LockingClassAttribute.WriteBlock)]public int function()
    {
        if (condition)
            return 0;
        return 1;
    }
    //Would Inherit [LockingClassAttribute(LockingClassAttribute.ReadWriteBlock)]
    public int function2()
    {
        if (condition)
            return 0;
        return 1;
    }
}

Is this possible to do?

2 Answers2

2

This is an example of aspect orientated programming. It's not directly available in C#, but you can use PostSharp to do this sort of thing.

Take a look at the OnMethodBoundaryAspect class, which allows you to run code before a method is run and after it completes.

Sean
  • 60,939
  • 11
  • 97
  • 136
1

What you are after is called aspect oriented programming. I have never applied it myself, but there are a few ready-made solutions. See e.g.: Aspect Oriented Programming in C#

Community
  • 1
  • 1
Grzenio
  • 35,875
  • 47
  • 158
  • 240