Reputation: 65564
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
.
Is there a way to use it (or something equivalent) for async methods that return a Task
?
Upvotes: 6
Views: 1142
Reputation:
Is there a way to use it (or something equivalent) for async methods that return a
Task
?
Same as with any value-returning function: wrap the call in a helper method returning void
, "returning" the value through a ref
parameter. 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.
[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;
}
Upvotes: 4
Reputation: 660004
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.
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.
Put another way: what would you expect this to do:
Foo(BarAsync());
if Foo
takes a Task
and BarAsync
is removed?
Upvotes: 12