How do different Async/Await modes in C# affect execution time?
Asynchronous waiting: waiting and non-waiting (ignored after startup)
Detailed code explanation
Consider the following code:
<code class="language-csharp">static async Task Callee() { await Task.Delay(1000); } static async Task Caller() { Callee(); // #1 启动后忽略 await Callee(); // #2 >1s Task.Run(() => Callee()); // #3 启动后忽略 await Task.Run(() => Callee()); // #4 >1s Task.Run(async () => await Callee()); // #5 启动后忽略 await Task.Run(async () => await Callee()); // #6 >1s } static void Main(string[] args) { var stopWatch = new Stopwatch(); stopWatch.Start(); Caller().Wait(); stopWatch.Stop(); Console.WriteLine($"Elapsed: {stopWatch.ElapsedMilliseconds}"); Console.ReadKey(); }</code>
Calling logic
#1: The simplest way to ignore after startup. #2: Simply wait. #3: Start an async method on a thread pool thread and ignore the result. #4: Start an asynchronous method on a thread pool thread and wait for its completion asynchronously. #5: Same as #3. #6: Same as #4.
Task.Run and asynchronous Lambda expressions
Although Task.Run will start a new thread, Task.Run(async => ...) is equivalent to Task.Factory.StartNew(async => ...), which will be created on the thread pool A new task and start it immediately.
Notes to ignore after startup
It is important to note that methods ignored after startup may cause unhandled exceptions, causing the application to crash. Therefore, it is important to carefully consider the impact before using them.
The above is the detailed content of How Do Different Async/Await Patterns Impact Execution Time in C#?. For more information, please follow other related articles on the PHP Chinese website!