查找未等待的异步方法调用

编程入门 行业动态 更新时间:2024-10-23 09:22:54
本文介绍了查找未等待的异步方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在将ASP.NET应用程序迁移到异步/等待模型时,我偶然发现了一个相当危险的场景.

I've just stumbled across a rather dangerous scenario while migrating an ASP.NET application to the async/await model.

这种情况是,我使方法异步:async Task DoWhateverAsync(),将接口中的声明更改为Task DoWhateverAsync(),并希望编译器通过该警告.好吧,祝你好运.通过接口将对象注入的任何地方,都不会发生警告. :-(

The situation is that I made a method async: async Task DoWhateverAsync(), changed the declaration in the interface to Task DoWhateverAsync() and hoped that the compiler would tell me where the code now is wrong, via that Warning. Well, tough luck. Wherever that object gets injected via the interface, the warning doesn't happen. :-(

这很危险.有什么方法可以自动检查返回任务的未等待的方法吗?我不介意太多警告,但我不想错过任何一个警告.

This is dangerous. Is there any way to check automatically for non-awaited methods that return tasks? I don't mind a few warnings too many, but I wouldn't want to miss one.

这是一个例子:

using System.Threading.Tasks; namespace AsyncAwaitGames { // In my real case, that method just returns Task. public interface ICallee { Task<int> DoSomethingAsync(); } public class Callee: ICallee { public async Task<int> DoSomethingAsync() => await Task.FromResult(0); } public class Caller { public void DoCall() { ICallee xxx = new Callee(); // In my real case, the method just returns Task, // so there is no type mismatch when assigning a result // either. xxx.DoSomethingAsync(); // This is where I had hoped for a warning. } } }

推荐答案

最后,我们使用roslyn查找忽略了Task或Task<>的返回值的所有实例:

In the end, we used roslyn to find all instances where a return value of Task or Task<> was ignored:

if (methodSymbol.ReturnType.Equals(syntaxNodeAnalysisContext.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Task).FullName))) { // For all such symbols, produce a diagnostic. var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), methodSymbol.ToDisplayString()); syntaxNodeAnalysisContext.ReportDiagnostic(diagnostic); } if (((INamedTypeSymbol) methodSymbol.ReturnType).IsGenericType && ((INamedTypeSymbol) methodSymbol.ReturnType).BaseType.Equals(syntaxNodeAnalysisContext.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Task).FullName))) { // For all such symbols, produce a diagnostic. var diagnostic = Diagnostic.Create(Rule, node.GetLocation(), methodSymbol.ToDisplayString()); syntaxNodeAnalysisContext.ReportDiagnostic(diagnostic); }

更多推荐

查找未等待的异步方法调用

本文发布于:2023-11-10 02:18:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!