First I used async delegates in this way:
public async Task TestWithAsyncDelegate()
{
await MethodWithAsyncDelegate(async (counter) => await AsyncLoad(counter));
}
But after some time, I found that if the used delegate contains only one call, it can be simplified to:
public async Task TestWithoutAsyncDelegate()
{
await MethodWithAsyncDelegate(counter => AsyncLoad(counter));
}
Is this code equivalent? In this case, embedding lambda in another delegate, it is redundant in my opinion. So I am using it.
Does somebody have an explanation why?
This approach cannot be used if called lambda has to await in its body:
public async Task TestWithMultipleCalls()
{
await MethodWithAsyncDelegate(async (counter) =>
{
await Task.Delay(10);
await AsyncLoad(counter);
});
}
Complete code follows:
public class AsyncDelegateTests
{
[Fact]
public async Task TestWithAsyncDelegate()
{
await MethodWithAsyncDelegate(async (counter) => await AsyncLoad(counter));
}
[Fact]
public async Task TestWithoutAsyncDelegate()
{
await MethodWithAsyncDelegate(counter => AsyncLoad(counter));
}
[Fact]
public async Task TestWithMultipleCalls()
{
await MethodWithAsyncDelegate(async (counter) =>
{
await Task.Delay(10);
await AsyncLoad(counter);
});
}
/// <summary>
/// simulate async work
/// </summary>
private async Task AsyncLoad(int counter)
{
await Task.Delay(10);
}
private async Task MethodWithAsyncDelegate(Func<int, Task> asyncDelegate)
{
for (int i = 0; i < 10 ; i++)
{
await asyncDelegate(i);
}
}
}