c# - 如何删除 StyleCop 警告“此异步方法缺少 'await' 运算符并将同步运行”而不从签名中删除异步
问题描述
父对象和大多数子对象都有异步并使用等待。StyleCop 正在观看并在一个儿童班级中因缺乏等待而感到不适。
当您无法删除异步签名时,让 StyleCop 满意的最佳方法是什么?
例如:
class Program
{
static void Main(string[] args)
{
var t = DownloadSomethingAsync();
Console.WriteLine(t.Result);
}
public delegate Task<string> TheDelegate(string page);
static async Task<string> DownloadSomethingAsync()
{
string page = "http://en.wikipedia.org/";
var content = await GetPageContentAsync(page);
return content;
}
static async Task<string> GetPageContentAsync(string page)
{
string result;
TheDelegate getContent = GetNotOrgContentAsync;
if (page.EndsWith(".org"))
{
getContent = GetOrgContentAsync;
}
result = await getContent(page);
return result;
}
static async Task<string> GetOrgContentAsync(string page)
{
string result;
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
result = await content.ReadAsStringAsync();
}
return result;
}
static async Task<string> GetNotOrgContentAsync(string page)
{
return await Task.FromResult("Do not crawl these");
// removing async will cause "Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'
}
}
找到了解决方案——为谷歌搜索创建这个以轻松找到。
您还可以使用此处提到的警告抑制:抑制来自空异步方法的警告
// 编辑以删除关于日志记录的争论,这个问题与任何方式无关,只是一个例子。
// 编辑以强制要求异步,因为这让人们感到困惑
解决方案
如果你什么都不做await
,那么只需async
从方法声明中删除关键字并返回Task.CompletedTask
:
public override Task DoMyThing()
{
// ..
return Task.CompletedTask; // or Task.FromResult(0); in pre .NET Framework 4.6
}
因为基类中的虚方法被标记为async
并不意味着覆盖也需要被标记async
。async
关键字不是方法签名的一部分。
推荐阅读
- javascript - 如何最大化 Electron 中的每个“window.open”调用?
- wordpress - 为什么我的网站与 WordPress rss RewriteRule 有问题
- css - 在维基百科中的文本下对齐表格
- wagtail - 基于指定页面字段的值的分支工作流
- python-3.x - 如何编写 Odoo 记录规则?
- java - 这个 NIO 读取是如何在幕后工作的?
- node.js - 猫鼬根据条件从数组中返回一个对象
- c++ - btRaycastVehicle 的 btWheelInfo 旋转不正确
- python - 大于 256 的 Python 整数变量的对象 ID
- javascript - 在使用 jQuery 创建新的 html 元素时指定所需的属性