【发布时间】:2014-01-30 20:47:11
【问题描述】:
使用PostSharp 使用OnEntry 和OnExit 方法为OnMethodBoundaryAspect 包装带有AOP 日志记录的WCF 服务调用。
进程:
OnEntry()被调用,DateTime表示调用开始的信号存储在属性中,并且异步任务在方法结束之前启动,同时该任务继续开。此任务格式化有关服务调用的一些信息以进行记录,并且可能需要一些时间。这些值作为属性存储在此类中以进行日志记录。
OnExit()被调用,另一个DateTime表示呼叫结束的信号被存储。此时我需要确保以OnEntry()方法启动的任务已完成,并且所有属性都已准备好记录到数据库中。
问题是如何确保在OnEntry() 开始的任务已完成以在OnExit() 中使用?我考虑过设置一个布尔值,while(false) {Thread.Sleep(100);},然后在为真时结束,但由于某种原因感觉不对。
下面是我目前为此设置的代码。
class LogMethodCallAttribute : OnMethodBoundaryAspect
{
Int32 userId;
String methodCall;
String ip;
DateTime entryTime;
DateTime exitTime;
/// Performs tasks on a Method before its execution.
public override void OnEntry(MethodExecutionArgs args)
{
// Set OnEntry Time
entryTime = DateTime.Now;
if (ConfigurationManager.AppSettings["AOPLoggingEnabled"] == "1")
{
MessageProperties prop = OperationContext.Current.IncomingMessageProperties;
// Queue the logging to run on the ThreadPool so the service can finish the request.
Task.Factory.StartNew(() => SetUpLog(args, prop));
}
}
public override void OnExit(MethodExecutionArgs args)
{
// Set OnExit Time
exitTime = DateTime.Now;
// Need to make sure the Task running SetUpLog is complete and all props set.
// Log the details of this method call.
Logs.LogWebServiceCall(userId, methodName, ip, entryTime, exitTime);
}
// Format details for logging.
private void SetUpLog(MethodExecutionArgs args, MessageProperties prop)
{
// Retrieve all the required data and do any formatting.
userId = ...;
methodCall = ...;
ip = ...;
}
}
【问题讨论】:
-
将从
Task.Factory.StartNew返回的任务存储在一个vriable中,并将Wait存储在OnExit中。
标签: c# wcf asynchronous postsharp