Find awaitable methods in code with Visual Studio

只谈情不闲聊 提交于 2020-01-04 01:50:50

问题


I have a problem where async methods are being called in the code without await in front of it. Is there a way to find all the awaitable methods that do not have await?

Edit - I'm particularly concerned with the scenario where multiple async methods are being called (ignoring the return values), but only one has await which is enough to make Visual Studio not warn about it.


回答1:


If you use ReSharper and turn solution-wide analysis on, your methods that are returning tasks that are not being awaited will have the Task portion of the method signature grayed out due to "return value is not used." The caveat here is that this will only find methods that are not being awaited anywhere in your solution; the warning will go away after one or more usages are updated to await (or use/reference the Task).

If you're looking for async methods that don't contain an await call (meaning they don't need to be labeled async), ReSharper will tell you about that too in a similar fashion.

    class AClass
    {
        public async void Foo() //async grayed out
        {
            DoSomethingAsync();
            Console.WriteLine("Done");
        }

        public Task<bool> DoSomethingAsync() //Task<bool> grayed out
        {
            return Task.Run(() => true);
        }    
    }

Note this will not work if you have code that looks like this:

    class AClass
    {
        public async void Foo()
        {
            bool b = DoSomethingAsync().Result;
            Console.WriteLine("Done");
        }

        public Task<bool> DoSomethingAsync()
        {
            return Task.Run(() => true);
        }    
    }

The async keyword, if present, will still be flagged, which means you can probably figure out pretty quickly a Task is not being awaited, but if the calling method is not marked async you are out of luck.



来源:https://stackoverflow.com/questions/31276479/find-awaitable-methods-in-code-with-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!