问题描述
public void runAction(Action theAction)
{
theAction();
}
如何确保“异步”委托无法传递给方法?换句话说,我想禁止以下内容:
public void doStuff()
{
runAction(async delegate ()
{
await doAsyncStuff();
});
}
我想禁止将“async”委托传递给同步“runAction”方法的原因是为了防止发生无声的错误。例如,如果'runAction'有两个版本(同步和异步),并且用户不小心将异步委托传递给同步一个,编译器和程序都会抛出错误,但可能会出现意想不到的后果。>
解决方法
如何确保无法将 async
委托传递给该方法?
不能,因为匿名异步函数可以转换为 void
委托。
然而,您可以做的是引入一个接受 Func<Task>
的重载,如果传递了 async
委托,它将被解决。
这将允许您以不同的方式处理异步委托:
public void RunAction(Action theAction)
{
theAction();
}
public void RunAction(Func<Task> theAction)
{
// do something different with an async delegate..
}
虽然这不会阻止编译时错误,但您可以抛出异常或记录该方法使用不正确的事实,而不是让它静默错误。
,Timothy Stepanski 的链接评论帮助我进行了检查,如果检测到委托是异步的,则会抛出异常:
Check if Action is async lambda
public void runAction(Action theAction)
{
var IsAsync = theAction.Method.IsDefined(typeof(AsyncStateMachineAttribute));
theAction = IsAsync ? throw new Exception("async delegates are not allowed") : theAction;
theAction();
}