Some code I just wrote follows.
It demonstrates applying a PostSharp aspect to a method for the purposes of recording the duration of the method invocation in an asynchronous manner - so that if the logging process is slow then this performance penalty is not seen by the caller of the method decorated with the aspect.
It seems to work, with MyFirstMethod completing, the logging method being set off in a separate thread, and MySecondMethod running on in parallel. The idea is that methods within a very highly-trafficked web application (i.e. a highly multi-threaded environment) be decorated with similar instrumentation.
What are the pitfalls of doing so? (e.g. I am concerned about reaching a limit on the number of threads permitted at any given time).
using System;
using System.Threading.Tasks;
using NUnit.Framework;
using PostSharp.Aspects;
namespace Test
{
[TestFixture]
public class TestClass
{
[Test]
public void MyTest()
{
MyFirstMethod();
MySecondMethod();
}
[PerformanceInstrument]
private void MyFirstMethod()
{
//do nothing
}
private void MySecondMethod()
{
for (int x = 0; x < 9999999; x++);
}
}
[Serializable]
public class PerformanceInstrument : MethodInterceptionAspect
{
public override void OnInvoke(MethodInterceptionArgs args)
{
var startDtg = DateTime.Now;
args.Proceed();
var duration = DateTime.Now - startDtg;
Task.Factory.StartNew(() => MyLogger.MyLoggingMethod(duration)); //invoke the logging method asynchronously
}
}
public static class MyLogger
{
public static void MyLoggingMethod(TimeSpan duration)
{
for (int x = 0; x < 9999999; x++);
Console.WriteLine(duration);
}
}
}