[英]How to remove StyleCop warning “This async method lacks 'await' operators and will run synchronously” without removing async from signature
[英]This async method lacks 'await' operators and will run synchronously
我的程序有以下語句的 3 個警告:
此異步方法缺少“等待”運算符,並且將同步運行。 考慮使用 'await' 運算符來等待非阻塞 API 調用,或使用 'await Task.Run(...)' 在后台線程上執行 CPU 密集型工作。
嘗試告訴我的警告是什么? 我該怎么辦?
這是我的代碼:它是否使用多線程運行?
static void Main(string[] args)
{
Task task1 = new Task(Work1);
Task task2 = new Task(Work2);
Task task3 = new Task(Work3);
task1.Start();
task2.Start();
task3.Start();
Console.ReadKey();
}
static async void Work1()
{
Console.WriteLine("10 started");
Thread.Sleep(10000);
Console.WriteLine("10 completed");
}
static async void Work2()
{
Console.WriteLine("3 started");
Thread.Sleep(3000);
Console.WriteLine("3 completed");
}
static async void Work3()
{
Console.WriteLine("5 started");
Thread.Sleep(5000);
Console.WriteLine("5 completed");
}
async
關鍵字本身並沒有多大作用。 從您的代碼中刪除它,您的代碼將完全相同。
async
什么作用?
await
關鍵字await
進行轉換。Task
。 但是,如果你 a) 在你的方法體中沒有任何await
並且 b) 是void
返回,那么不會有什么特別的東西。 編譯器警告確實試圖澄清這一點 - 沒有任何await
的async
方法只是簡單的沒有意義。 await
是此功能中更重要的部分。
如果您使用同步方法覆蓋和異步方法,您可以:
await Task.Run(() => [你的同步方法]);
是的,您的代碼可能會使用多線程。 但是,如果您只是刪除async
關鍵字,它仍然會這樣做。 由於您沒有解釋為什么它在那里,我建議將其刪除。
如果你想要一個 async/await 模式,你可以使用Task.Delay()
但我建議你在使用它之前閱讀更多關於 async/await 的內容:
static async void Work3()
{
Console.WriteLine("5 started");
await Task.Delay(5000);
Console.WriteLine("5 completed");
}
您使用了“ async
”關鍵字和方法,表明 Work1()、Work2() 和 Work3() 方法是異步執行的,但您沒有使用“ await
”關鍵字。所以它是同步執行的。使用“ await
”關鍵字如果你想異步執行它。
static async void Work1()
{
Console.WriteLine("10 started");
await Task.Delay(10000);
Console.WriteLine("10 completed");
}
static async void Work2()
{
Console.WriteLine("3 started");
await Task.Delay(3000);
Console.WriteLine("3 completed");
}
static async void Work3()
{
Console.WriteLine("5 started");
await Task.Delay(5000);
Console.WriteLine("5 completed");
}
您使用關鍵字async
指定了方法(Work1、Work2、Work3),但這些方法中的任何代碼都沒有使用await
運算符來調用異步調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.