c# - 方法异步的拦截器?
问题描述
如果发生某种情况,我可以拦截正在运行的方法吗?
这就是我想要做的:
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 等内部......)
解决方案
在每个方法调用之间检查拦截器的唯一原因是:
- 如果发出取消信号,则不得运行这些方法
- 这些方法是同步的,需要时间来执行
在大多数其他情况下,这只是浪费时间并使代码更难阅读。
如果其中的方法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);
}
}
推荐阅读
- go - Jenkins 无法从 github 下载依赖项
- java - 如何让我的 Spring Boot 应用程序识别此服务?
- gitlab-ci - Gitlab CI/CD 动态切换作业到手动模式
- javascript - 如何使用 Express Validator 验证图像扩展?
- python-2.7 - 为什么我在导入模块时得到了一些 python 函数,而没有其他函数?
- javascript - 使用 JavaScript 定位没有选择器的标签元素
- javascript - 选择 js 中断选项和重复输入
- c - 算术级数系列的输出在 C 中不正确
- html - 如何让 display:grid(或 ms-grid)在 Internet Explorer 11 中工作?
- python - sqlalchemy @hybrid_property v @property,@hybrid_method v @classmethod