Like I said in my last post, Postsharp is a very interesting AOP tool for .net. Most of the starting up samples relate to the OnMethodBoundaryAspect. I find OnMethodBoundaryAspect really close to how decorators work in Python. In fact, tracing and logging are two of the most common examples found for both on the net. But there are a couple of more samples of decorators in Python than there are in Postsharp, so I will trying to even things a little by posting a synchronization example (which is another common example of python decorators).
The idea will be to create a SynchronizedAttribute that basically works like Java's synchronized keyword. There are many reasons why this type of synchronization isn't the brightest idea, but this is only an example dammit!! So basically what I'm trying to achieve is:
[Synchronized]
public void SynchronizedMethod()
{
//.. do sync'd stuff
}
So that it is equivalent to this:
public void SynchronizedMethod()
{
lock(this)
{
//.. do sync'd stuff
}
}
Basically, the idea is to do a more elegant and readable version of the second code (ok, it's really just a new sample). After adding the Postsharp.Public and Postsharp.Laos references. You create a class named SynchronizedAttribute with the following code:
[Serializable]
public class SynchronizedAttribute:OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
Monitor.Enter(eventArgs.Instance);
}
public override void OnExit(MethodExecutionEventArgs eventArgs)
{
Monitor.Exit(eventArgs.Instance);
}
}
That's it!! Now you can have a beautiful synchronization attribute. The best thing about this is that you can change this code to do a more powerful synchronization (like a timed lock) without changing the rest of your code. You can also validate that the method is not static at compile time, so that you don't fall into a NullException you can check at compile time if the function is static.
public override bool CompileTimeValidate(System.Reflection.MethodBase method)
{
if (method.IsStatic)
{
SynchronizedMessageSource.instance.Write(SeverityType.Error, "staticError", new object[] { method.Name});
return false;
}
return true;
}
This will throw you a message in visual studio if the Attribute is added to an static method.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5