首页 > 解决方案 > 如何删除 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>'
  }

}

找到了解决方案——为谷歌搜索创建这个以轻松找到。

您还可以使用此处提到的警告抑制:抑制来自空异步方法的警告

// 编辑以删除关于日志记录的争论,这个问题与任何方式无关,只是一个例子。

// 编辑以强制要求异步,因为这让人们感到困惑

标签: c#asynchronousasync-awaitstylecop

解决方案


如果你什么都不做await,那么只需async从方法声明中删除关键字并返回Task.CompletedTask

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

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


推荐阅读