Flag async methods that return a task with the Conditional attribute?

System.Diagnostics.ConditionalAttribute really useful for cutting off fragments of debugging code without using compiler directives, but it is only compatible with methods that return void .
Is there a way to use it (or something similar) for asynchronous methods that return a Task ?

+5
source share
2 answers

No.

The void method can be removed without any problems, because the net impact on the evaluation stack is the same regardless of whether the method call: zero exists there.

A non-empty method cannot be deleted, because if it is deleted, there are zero things on the stack, and if it is not deleted, there is one thing on the stack: a reference to the task.

Put another way: what do you expect from this:

 Foo(BarAsync()); 

if Foo removes Task and BarAsync ?

+8
source

Is there a way to use it (or something similar) for asynchronous methods that return a Task ?

Same as with any function returning a value: end the call in a helper method, returning void , "returning" the value via the ref parameter. Yes, this is clumsy, but in this way you are forced to write an initializer for the returned parameter, and this initializer is how it can be valid even if the call is deleted: you can never get uninitialized values.

 [Conditional("DEBUG")] public void FooAsync(ref Task task) { Func<Task> impl = async () => { // ... }; task = impl(); } 

Using:

 public async Task CallFoo() { var task = Task.CompletedTask; FooAsync(ref task); await task; } 
+4
source

Source: https://habr.com/ru/post/1265978/


All Articles