【问题标题】:How can I stop a method's execution using PostSharp?如何使用 PostSharp 停止方法的执行?
【发布时间】:2014-04-10 08:14:36
【问题描述】:

目前我正在尝试开发一个解决方案,该解决方案将检查一个方法是否已被执行,以及自上次执行以来是否已经过了一段时间,鉴于它是并且时间已经过去,我想从 OnEntry 跳过方法到 OnExit,而无需从方法本身实际执行任何代码。

种类:

public class CacheThisMethod : OnMethodBoundaryAspect
{
            public override void OnEntry(MethodExecutionArgs args)
            {
               if (isCached( args.Method.name)
                   {
                    args.MethodExecutionTag =  getReturnValue(args.Method.name)
                    //jump to OnExit
                   }
               else
                   {
                    //continue
                   }
            }
            public override void OnExit(MethodExecutionArgs args)
            {
               args.Method.ReturnValue = args.MethodExecutionTag;


             }
}

我怎样才能做到这一点?谢谢。

【问题讨论】:

  • 您确定不想将参数用作缓存中的键?
  • 我假设你知道你需要在 isCached 方法中做什么。

标签: c# postsharp aop


【解决方案1】:

以下对您的代码的修改显示了如何得到您想要的。

public class CacheThisMethod : OnMethodBoundaryAspect
{
        public override void OnEntry(MethodExecutionArgs args)
        {
           if (isCached( args.Method.name)
               {
                args.MethodExecutionTag =  getReturnValue(args.Method.name)
                OnExit(args);
               }
           else
               {
                //continue
               }
        }
        public override void OnExit(MethodExecutionArgs args)
        {
           //args.Method.ReturnValue = args.MethodExecutionTag;
            args.ReturnValue = args.MethodExecutionTag;
            args.FlowBehavior = FlowBehavior.Return;
        }
}

但是,如果您正在处理每个方法名称键,那么您可以为缓存的返回值使用一个简单的属性,因为当您将通知附加到方法时,将为您创建每个方面的单独实例。

如果没有理由跳转到 OnExit,那么只需在 OnEntry 方法调用 OnExit 方法时添加 FlowBehaviour 和返回值设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2016-07-14
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多