I want to implement a custom attribute that, using stopwatch, will measure the running time of the code. I connected the attribute to the main method. But nothing is displayed on the console. I do not understand how to write such an attribute correctly?

[AttributeUsage(AttributeTargets.All )] class TestAttribute : Attribute { private Stopwatch stopwatch; public void RunTime() { stopwatch = new Stopwatch(); stopwatch.Start(); } public void ShowTime() { stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); } } class Program { [TestAttribute] static void Main(string[] args) { } } 

    1 answer 1

    In your case, the RunTime and ShowTime methods are simply attribute methods: the assembly knows nothing about them and will not call before and after the method call, as you probably expected.

    The functionality you need is implemented in the OnMethodBoundaryAspect class from the PostSharp library. You can use as follows.

     [Serializable] [MulticastAttributeUsage(MulticastTargets.Method, Inheritance = MulticastInheritance.Multicast)] class TestAttribute : OnMethodBoundaryAspect { private Stopwatch stopwatch; public override void OnEntry(MethodExecutionArgs args) { stopwatch = new Stopwatch(); stopwatch.Start(); } public override void OnExit(MethodExecutionArgs args) { stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); } } 

    If you, like me, are interested in solving the problem without using PostSharp, I suggest you follow this question .