I'm wondering if I use async
and await
to excessively in my code and if there are (performance) penalties in doing so?
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?