【发布时间】:2014-10-21 22:22:11
【问题描述】:
没有按预期使用异步方法调用 PostSharp Aspect OnSuccess 方法。 当我等待 Async 方法时,在方法返回之前调用成功。 我的观点:
namespace PostSharpConcepts
{
[Serializable]
public class ProfilerAspect : OnMethodBoundaryAspect, IOnStateMachineBoundaryAspect
{
public ProfilerAspect()
{
ApplyToStateMachine = false;
}
public override void OnEntry(MethodExecutionArgs args)
{
args.MethodExecutionTag = Stopwatch.StartNew();
}
public override void OnSuccess(MethodExecutionArgs args)
{
Stopwatch sw = (Stopwatch) args.MethodExecutionTag;
sw.Stop();
string message = string.Format("{0} Executed in {1} seconds, Class : {2}", args.Method.Name, (float)sw.ElapsedMilliseconds / 1000, args.Method.DeclaringType.FullName);
Debug.WriteLine("OnSuccess");
Logger.LogBase(Logger.LogLevel.Debug, message);
}
public override void OnResume(MethodExecutionArgs args)
{
Stopwatch sw = (Stopwatch)args.MethodExecutionTag;
sw.Stop();
string message = string.Format("{0} Executed in {1} seconds, Class : {2}", args.Method.Name, (float)sw.ElapsedMilliseconds / 1000, args.Method.DeclaringType.FullName);
Debug.WriteLine("OnResume");
Logger.LogBase(Logger.LogLevel.Debug, message);
}
}
}
调用代码:
namespace PostSharpConcepts
{
[ProfilerAspect]
class Program
{
static void Main(string[] args)
{
DoSomething();
Console.ReadLine();
}
private async static void DoSomething()
{
Debug.WriteLine("DoSomething - start");
await Task.Run(() => System.Threading.Thread.Sleep(2000));
Debug.WriteLine("DoSomething - end");
}
}
}
这是输出: DoSomething - 开始 成功 DoSomething - 结束
预期输出将根据非异步调用: DoSomething - 开始 做某事 - 结束 成功
【问题讨论】:
-
确保您运行的是 PostSharp 3.1 或更高版本。
-
应该使用 PostSharp Express 添加