方法异步的拦截器?
Interceptor for methods async?
如果某些情况发生,我可以拦截 运行 方法吗?
这就是我想要做的:
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);
}
}
如果某些情况发生,我可以拦截 运行 方法吗?
这就是我想要做的:
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);
}
}