【问题标题】:IAsyncInterceptor stuck in recursive loopIAsyncInterceptor 陷入递归循环
【发布时间】:2023-03-17 05:23:01
【问题描述】:

我正在遵循一种异步拦截简单方法的方法:https://github.com/wswind/Learn-AOP/blob/master/AutofacAsyncInterceptor/CallLoggerAsyncInterceptor.cs

为了这个问题,此代码的简化版本可能是:

private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
{
    // do some async stuff
    // invoke the original method
    invocation.Proceed();
    var task = (Task<TResult>)invocation.ReturnValue;
    var result = await task;
    return result;
}

在实现它之前我确实认为它是递归的 - 因为invocation.Proceed() 会再次被拦截,它本身会再次调用Proceed(),依此类推。

我已经看到了很多关于这个库的 SO 的建议,它被广泛接受为一种拦截异步的方法,我错过了什么会使这个方法不递归?它陷入了无限循环,但对我来说这是意料之中的。

编辑

我发现这是什么,将其缩小为“异步内容”,如下所示:

await MyAsyncMethod();

当MyAsyncMethod 是:

public async Task MyAsyncMethod()
{
   // await somethingElse();
}

当我在等待一个自己在等待的任务时,它会中断 invocation.Proceed() 并且我被困在一个循环中。

对此的任何帮助都非常感谢!

【问题讨论】:

  • 听起来像invocation.Proceed() 可能是blocking。
  • @GSerg - 感谢您的回复!我确实很有趣地阅读了这篇文章 - 但它并没有锁定并冻结它实际上只是循环回到这个方法的开始。然后再次调用自身。就好像invocation.Proceed 根据有 2 个或更多异步的事实改变了它的行为。如果我将somethingElse 更改为同步执行(即.Result),一切正常。但出于显而易见的原因,我不想这样做。

标签: c# .net async-await interceptor castle


【解决方案1】:

也可以试试https://fs7744.github.io/Norns.Urd/index.html

它使用简单的方式来支持异步

public class AddTenInterceptorAttribute : AbstractInterceptorAttribute
{
    public override void Invoke(AspectContext context, AspectDelegate next)
    {
        next(context);
        AddTen(context);
    }

    private static void AddTen(AspectContext context)
    {
        if (context.ReturnValue is int i)
        {
            context.ReturnValue = i + 10;
        }
        else if(context.ReturnValue is double d)
        {
            context.ReturnValue = d + 10.0;
        }
    }

    public override async Task InvokeAsync(AspectContext context, AsyncAspectDelegate next)
    {
        await next(context);
        AddTen(context);
    }
}


[AddTenInterceptor]
public interface IGenericTest<T, R> : IDisposable
{
    // or
    //[AddTenInterceptor]
    T GetT();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 2014-06-23
    • 2010-11-09
    • 1970-01-01
    相关资源
    最近更新 更多