首页 > 解决方案 > 方法异步的拦截器?

问题描述

如果发生某种情况,我可以拦截正在运行的方法吗?

这就是我想要做的:

await Task.Run(() => { Interceptor(); });
await Task.Run(() => { A(); });

private void Interceptor()
{
      //if some condition here, PAUSE whatever is running in A(), do "something" and then re-run A()- wheter where it stopped or re-run the whole method A again
}

private void A()
{
    B();
    C();
    .....
    D();
}

这就是我正在做的事情:

await Task.Run(() => { A(); });

private void Interceptor()
{
      if(condition)
      {
           Foo();
      }
}

private void A()
{
    Interceptor();
    B();
    Interceptor();
    C();
    Interceptor();
    .....
    Interceptor();
    D();
    Interceptor();
}

有没有办法做到这一点?关键是我有一个非常动态A()的方法,这种Interceptor情况可能发生在任何时候......(包括在方法 B、C、D 等内部......)

标签: c#interceptor

解决方案


在每个方法调用之间检查拦截器的唯一原因是:

  • 如果发出取消信号,则不得运行这些方法
  • 这些方法是同步的,需要时间来执行

在大多数其他情况下,这只是浪费时间并使代码更难阅读。

如果其中的方法A()是异步的,请停止阅读此处并改用取消令牌。

如果方法是同步的并且需要时间,或者必须中止,最好只创建一个管道依次执行每个方法:

public static class ExecutionExtensions
{
    public static void Execute(this IEnumerable<Action> pipeline, Func<bool> cancellationFunction)
    {
        foreach (var action in pipeline)
        {
            action();
            if (cancellationFunction())
                break;
        }
    }
}

然后只需定义流程:

// Requires that the methods are in the same class
var a = new List<Action> { B, C, D, E };

并执行它:

// interceptor must return true when the execution should be halted.
a.Execute(Interceptor);

完整代码:

public class AClass
{
    private void B()
    {

    }

    private void C()
    {

    }

    private void D()
    {

    }

    private bool Interceptor()
    {
        return false;
    }

    public void A()
    {
        var pipeline = new List<Action> { B, C, D };
        pipeline.Execute(Interceptor);
    }
}

推荐阅读