Tech Off Thread

3 posts

Code Execution Monitoring with Attributes?

Back to Forum: Tech Off
  • JoshB

    Not even really sure how to ask the question and it doesn't stem from any real world problem I'm having, mostly just pondering.

    Is there a way in C# to step outside the actual execution context of your code and modify it's behavior, or at least monitor it?

    The question came up this morning about dealing with recursive methods and I thought there has to be a way to monitor the actual execution of the methods and maybe do a count of the number of calls so you could terminate the process somehow. Also doing this without some sort of object oriented approach that you have to modify the method signitures to pass around a state object. Something like

    [RecurseNoMoreThan(100, Method3)]
    void Main()

    void Method1()

    void Method2()

    void Method3()

    I know, lame example but hopefully gets my intent across. Maybe something for code profiling or logging.

    [ExecutionLog(LogItemType.ExecutionTime | LogItemType.ReturnValue)]
    String Main()
       return "Something Cool"

    Again, was just wondering. What about outside of .NET? Are there any languages out there that do something similar?

    Thanks for your time!

  • littleguru

    What you question is called AOP: Aspect-oriented programming. Spring .NET is a good framework for that. It's not possible to add custom code to a method, by using System.Reflection.Emit, but you can hook yourself into classes that are provided by remoting to do AOP. But Spring .NET implements that under hood and you can just use it Smiley

    A sample on how to do it on your own is found here.

    Edit: Spring is also available for JAVA - it actually comes from there. Just to answer your second question Wink

  • Andrew Davey

    Nemerle has syntactic macros that look exactly like that.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.