【发布时间】:2019-02-22 16:47:01
【问题描述】:
父对象和大多数子对象都有异步并使用等待。 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>'
}
}
找到了解决方案 - 为 google 搜索创建此解决方案以便轻松查找。
您还可以使用此处提到的警告抑制:Suppress warning from empty async method
// 编辑以删除关于日志记录的争论,该问题与任何方式无关,仅作为示例。
// 编辑以强制要求异步,因为这会让人们感到困惑
【问题讨论】:
-
那为什么是
async这个方法呢?如果您不打算等待返回,请不要使用 async 修饰符。 -
第二点基于您正在记录某些内容的评论。使用适当的日志框架,它们不是微不足道的事情,你自己构建并且你会;根本不需要担心事情的异步方面。
-
async不是签名的一部分。从外面看,没有人知道你是否使用了async,只是它返回一个Task或一些Task<T>。 -
@DavidG 我想知道你在哪里读到 OP 没有使用正确的日志框架?
-
@huysentruitw 日志框架往往不使用异步方法。
标签: c# asynchronous async-await stylecop