I'm wondering if I use async
and await
to excessively in my code and if there are (performance) penalties in doing so?
(我想知道我是否在代码中过度使用了async
和await
并await
(性能)方面的惩罚?)
What I often do:
(我经常做什么:)
static void Main()
{
var result = Task<int>.Run (()=> S1Async(1)).Result;
Console.WriteLine(result);
}
static async Task<int> WrapperAsync(Func<int, Task<int>> func) => await func(2);
static async Task<int> S1Async(int x) => await WrapperAsync(async t=> await S2Async(x * t));
static async Task<int> S2Async(int x) => await WrapperAsync(async t=> await S3Async(x * t));
static async Task<int> S3Async(int x) => await WrapperAsync(async t=> await S4Async(x * t));
static async Task<int> S4Async(int x) => await Task.FromResult(x * 10);
I think the async-awaits can be skipped and that this code is similar:
(我认为可以跳过异步唤醒,并且此代码类似:)
static void Main()
{
var result = Task<int>.Run(() => S1Async(1)).Result;
Console.WriteLine(result);
}
static Task<int> WrapperAsync(Func<int, Task<int>> func) => func(2);
static Task<int> S1Async(int x) => WrapperAsync(t => S2Async(x * t));
static Task<int> S2Async(int x) => WrapperAsync(t => S3Async(x * t));
static Task<int> S3Async(int x) => WrapperAsync(t => S4Async(x * t));
static Task<int> S4Async(int x) => Task.FromResult(x * 10);
When tasks are nested with just one task per level, is it safe to skip async/await?
(当任务只嵌套一个级别的每个任务时,跳过异步/等待是否安全?)
Both code-samples gives the same result in LinqPad, so I assume they are similiar, but maybe there are side-effects I should be aware of?
(这两个代码样本在LinqPad中给出的结果相同,因此我认为它们是相似的,但也许还有一些我应该注意的副作用?)
ask by Frode translate from so