我有一些函数需要记录它们所消耗的时间。
DBResult LongTask(DBCommand command)
{
...
}
有没有方法可以实现这个?
[LogTimeUsed()]
DBResult LongTask(DBCommand command)
{
...
}
我希望有一个类/函数,每次调用该函数时都会被调用,并且我可以注入自己的代码,获得对命令和DBResult的访问并记录函数执行所花费的时间。
我有一些函数需要记录它们所消耗的时间。
DBResult LongTask(DBCommand command)
{
...
}
[LogTimeUsed()]
DBResult LongTask(DBCommand command)
{
...
}
我希望有一个类/函数,每次调用该函数时都会被调用,并且我可以注入自己的代码,获得对命令和DBResult的访问并记录函数执行所花费的时间。
在.NET中没有内置的方法可以实现这个功能。
如果您不想使用任何第三方库(正如您在其中一个评论中所说),则进行代码编织或动态代理生成是一项很大的工作。在这种情况下,最好放弃使用属性并采用装饰器设计模式。这里有一个例子:
// Define an interface for the operation
public interface IMyLongRunningTask
{
DBResult longTask(DBCommand command);
}
// Define an implementation for the operation:
public class MyLongRunningTask : IMyLongRunningTask
{
public DBResult longTask(DBCommand command)
{
// code here
}
}
现在你可以为IMyLongRunningTask编写一个装饰器:
public class MyLongRunningTaskMonitor : IMyLongRunningTask
{
private readonly IMyLongRunningTask wrappedService;
private readonly ILogger logger;
public MyLongRunningTaskMonitor(IMyLongRunningTask wrapped,
ILogger logger)
{
this.wrappedService = wrapped;
this.logger = logger;
}
public DBResult longTask(DBCommand command)
{
var watch = Stopwatch.CreateNew();
var result = this.wrappedService.longTask(command);
this.logger.Log("longTask executed in " +
watch.ElapsedMilliseconds + " ms.");
return result;
}
}
MyLongRunningTaskMonitor
以在请求IMyLongRunningTask
时返回。例如:container.Register<IMyLongRunningTask>(() =>
new MyLongRunningTaskMonitor(
container.GetInstance<MyLongRunningTask>(),
container.GetInstance<ILogger>()
)
);
只是为了增加第三方工具列表,还有Spring AOP(Spring是一个大型且流行的框架,已从Java移植到.NET)
http://www.springframework.net/doc-latest/reference/html/aop.html