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

问题描述 投票:0回答:2

父对象和大多数孩子都有异步并使用等待。 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

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

//编辑强制所需的异步,因为这让人很困惑

c# asynchronous async-await stylecop
2个回答
5
投票

如果你没有await任何东西,那么只需从方法声明中删除async关键字并返回Task.CompletedTask

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

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


0
投票

选项:

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

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

跨项目抑制:

#pragma warning disable 1998

或抑制一种方法:

#pragma warning disable 1998
async Task Foo() {}
#pragma warning restore 1998
© www.soinside.com 2019 - 2024. All rights reserved.