我刚刚写的一些代码如下。
它演示了将 PostSharp aspect 应用于方法,以便以异步方式记录方法调用的持续时间 - 因此,如果日志记录过程很慢,则使用该 aspect 装饰的方法的调用者不会看到这种性能损失.
它似乎可以工作,随着 MyFirstMethod 的完成,日志记录方法在一个单独的线程中启动,并且 MySecondMethod 并行运行。这个想法是在一个非常高流量的 Web 应用程序(即一个高度多线程的环境)中的方法用类似的工具来装饰。
这样做的陷阱是什么?(例如,我担心在任何给定时间达到允许的线程数限制)。
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);
}
}
}