[英]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.