Identification Start and end method

I am creating Traces for a method and want it to be used with a custom attribute. I will decorate each method with TraceMethod .

eg:

 [TraceMethod()] public void SomeMethod() { } public class TraceMethod : Attribute { public void StartTrace(){} public void EndTrace(){} } 

So here

How to call StartTrace() before starting to execute SomeMethod and EndTrace() after completing SomeMethod ? Is it possible?

+7
c # custom-attributes
source share
3 answers

What you are trying to do is Aspect-Oriented Programming , which is currently not supported outside the box of the .NET world. You will have to use a third-party component; there are some there , both paid and open sources.

+2
source share

Perhaps a custom class is created that marks the scope of the function? Create an instance of the class at the beginning of the function and when the function exits the class, it goes out of scope and the destructor is called.

The sign of the constructor and destructor is the beginning and end of the function.

Edit: As noted, this does not mean that the destructor is called immediately after the object goes out of scope. It is better to use the using() block:

 public void SomeMethod() { using (TraceMethod trace = new TraceMethod()) { } } public class TraceMethod : IDisposable { public TraceMethod() { StartTrace(); } // Constructor public void Dispose() { EndTrace(); } // Gets called when leaving the using() block private void StartTrace() { ... } private void EndTrace() { ... } } 
0
source share

You can change the body of the method:

 public void SomeMethod() { var trace = new Trace(); try { ... rest of method } finally { trace.EndTrace(); } } public class TraceMethod : Attribute { public TraceMethod() => StartTrace(); public void StartTrace() { ... } public void EndTrace() { ... } } 
0
source share

All Articles