[英]Mark async methods that just return a Task with the Conditional attribute?
The System.Diagnostics.ConditionalAttribute
is really useful for sectioning off pieces of Debug code without needing to use compiler directives but it is only compatible with methods that return void
. System.Diagnostics.ConditionalAttribute
对于分割调试代码片段非常有用,无需使用编译器指令,但它只与返回void
方法兼容。
Is there a way to use it (or something equivalent) for async methods that return a Task
? 有没有办法为返回Task
异步方法使用它(或等效的东西)?
No. 没有。
A void method can be removed without any problem because the net effect on the evaluation stack is the same whether there is a method call there or not: zero. 可以毫无问题地移除void方法,因为无论是否存在方法调用,评估堆栈的净效果都是相同的:零。
A non-void method cannot be removed because in the case where it is removed, there are zero things on the stack, and in the case where it is not removed, there is one thing on the stack: a reference to a task. 无法删除非void方法,因为在删除它的情况下,堆栈上没有任何东西,并且在没有删除它的情况下,堆栈上有一件事:对任务的引用。
Put another way: what would you expect this to do: 换句话说:你期望这样做:
Foo(BarAsync());
if Foo
takes a Task
and BarAsync
is removed? 如果Foo
接受Task
并且删除了BarAsync
?
Is there a way to use it (or something equivalent) for async methods that return a
Task
? 有没有办法为返回Task
异步方法使用它(或等效的东西)?
Same as with any value-returning function: wrap the call in a helper method returning void
, "returning" the value through a ref
parameter. 与任何值返回函数相同:将调用包装在一个返回void
的helper方法中,通过ref
参数“返回”该值。 Yes, it's clumsy, but this way you're forced to write an initialiser for the return parameter, and that initialiser is how it can be valid even if the call is removed: you can never end up with uninitialised values. 是的,这很笨拙,但是这样你就不得不为return参数写一个初始化器,而初始化器就是如果它被删除的话它是如何有效的:你永远不会得到未初始化的值。
[Conditional("DEBUG")]
public void FooAsync(ref Task task) {
Func<Task> impl = async () => {
// ...
};
task = impl();
}
Usage: 用法:
public async Task CallFoo() {
var task = Task.CompletedTask;
FooAsync(ref task);
await task;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.