The attribute method is not called unless you name it manually. There are security attributes that call the CLR, but this is beyond the scope of this question, and in any case it will be useless.
There are ways to rewrite code at a different level. Source code pairing, IL weaving, etc.
You need to look at some way to change the IL and rewrite it to synchronize execution. Do not worry, you do not need to write all this. People have already done this. For example, you can use PostSharp .
Here's an article that gives an example
[Serializable] [DebuggerStepThrough] [AttributeUsage(AttributeTargets.Method)] public sealed class LogExecutionTimeAttribute : OnMethodInvocationAspect { private static readonly ILog Log = LogManager.GetLogger(typeof(LogExecutionTimeAttribute)); // If no threshold is provided, then just log the execution time as debug public LogExecutionTimeAttribute() : this (int.MaxValue, true) { } // If a threshold is provided, then just flag warnning when threshold exceeded public LogExecutionTimeAttribute(int threshold) : this (threshold, false) { } // Greediest constructor public LogExecutionTimeAttribute(int threshold, bool logDebug) { Threshold = threshold; LogDebug = logDebug; } public int Threshold { get; set; } public bool LogDebug { get; set; } // Record time spent executing the method public override void OnInvocation(MethodInvocationEventArgs eventArgs) { var sw = Stopwatch.StartNew(); eventArgs.Proceed(); sw.Stop(); var timeSpent = sw.ElapsedMilliseconds; if (LogDebug) { Log.DebugFormat( "Method [{0}{1}] took [{2}] milliseconds to execute", eventArgs.Method.DeclaringType.Name, eventArgs.Method.Name, timeSpent); } if (timeSpent > Threshold) { Log.WarnFormat( "Method [{0}{1}] was expected to finish within [{2}] milliseconds, but took [{3}] instead!", eventArgs.Method.DeclaringType.Name, eventArgs.Method.Name, Threshold, timeSpent); } }
Note. I changed the example from the article to use StopWatch instead of DateTime , because DateTime not accurate.
Sriram sakthivel
source share