Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute to wrap functions?

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?

like image 532
user3141117 Avatar asked May 17 '26 22:05

user3141117


1 Answers

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.

like image 77
Sean Avatar answered May 20 '26 10:05

Sean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!