繁体   English   中英

如何删除StyleCop警告“此异步方法缺少'await'运算符,将同步运行”,而不会从签名中删除异步

[英]How to remove StyleCop warning “This async method lacks 'await' operators and will run synchronously” without removing async from signature

父对象和大多数子对象具有异步功能并使用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>'
  }

}

找到了解决方案-为Google搜索找到easilly创建此解决方案。

您还可以按此处所述使用警告抑制: 从空的异步方法禁止警告

//编辑以删除有关日志记录的辩论,该问题与任何问题都无关,仅是示例。

//编辑以强制执行必需的异步操作,因为这会使人感到困惑

如果您不await任何内容,则只需从方法声明中删除async关键字,然后返回Task.CompletedTask

public override Task DoMyThing()
{
    // ..
    return Task.CompletedTask; // or Task.FromResult(0); in pre .NET Framework 4.6
}

因为基类中的虚方法被标记为async并不意味着覆盖也需要被标记为async async关键字不是方法签名的一部分。

选项:

在异步函数中添加一些代码:

return await Task.FromResult("Do not crawl these");

禁止整个项目:

#pragma warning disable 1998

或抑制一种方法:

#pragma warning disable 1998
async Task Foo() {}
#pragma warning restore 1998

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM