Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressions to identify async methods causes compiler warning

I am using an expression to identify a specific method in a class, and return the attribute of the method. When the method is async, the compiler gives me a warning that the method should be awaited.

Are there any other ways I could identify the method, or any way to suppress the warning, without using pragma? I would like not to use a string to identify the method.

Resharper suggests async/await, but async lambda expression cannot be converted to expression trees.

Other answers are extension methods for task, but then I would not be able to get the method with the attribute.

Example code:

class Program
{
    static void Main(string[] args)
    {
        var attributeProvider = new AttributeProvider();
        var attributeText = attributeProvider.GetAttribute<Program>(
            p => p.MethodA()); //Warning: Because this call is not awaited, ...
    }

    [Text("text")]
    public async Task<string> MethodA()
    {
        return await Task.FromResult("");
    }
}

public class AttributeProvider
{
    public string GetAttribute<T>(Expression<Action<T>> method)
    {
        var expr =(MethodCallExpression) method.Body;

        var attribute = (TextAttribute)Attribute.GetCustomAttribute(
            expr.Method, typeof(TextAttribute));

        return attribute.Text;
    }
}

public class TextAttribute : Attribute
{
    public string Text { get; set; }

    public TextAttribute(string text)
    {
        Text = text;
    }
}
like image 209
user10466899 Avatar asked Oct 29 '22 03:10

user10466899


1 Answers

Since it's just an Action<T>, the compiler sees that you are invoking a Task but not doing anything with it. In this case, that's deliberate so you could ignore the warning. To avoid the warning, you could add an overload of the GetAttribute method to take an Func<T,object> instead of an Action<T>.

public string GetAttribute<T1>(Expression<Func<T1,object>> method)

This way, the compiler will see that you are expecting a result (in this case a Task) and will assume you will do something with it and not warn you about not awaiting it.

like image 136
Eric Damtoft Avatar answered Nov 15 '22 05:11

Eric Damtoft