简体   繁体   中英

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

Parent object and most children have async and use await. StyleCop is watching and throwing a fit over lack of await in one child class.

What is the best way to make StyleCop happy when you can't remove the async signature?

For example:

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>'
  }

}

Found the solution -- creating this for google searching to find easilly.

You can also use warning suppression as mentioned over here: Suppress warning from empty async method

// edit to remove debate about logging, which the question was not about in any way and was just for an example.

// edit to force async required because that confused people

If you do not await anything, then simply remove the async keyword from the method declaration and return Task.CompletedTask :

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

Because the virtual method in the base class is marked as async doesn't mean the override needs to be marked as async as well. The async keyword is not part of the method signature.

Options:

Add a bit of code in your async function:

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

Suppress across project:

#pragma warning disable 1998

Or suppress on one method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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