What is the correct way to call Polly ExecuteAsync method?

Viewed 2965

Executing a Policy, I've see some people call ExecuteAsync like this:

...
.ExecuteAsync(async (ct) => await GetEmployeeAsync(employeeId, ct), cancellationToken);

And like this:

...
.ExecuteAsync(ct => GetEmployeeAsync(employeeId, ct), cancellationToken);

What is the difference and which one should be used?

1 Answers

In this simple case, there's no semantic difference. The version eliding async and await has an almost-immeasurable performance benefit.

In the general case, there are some pitfalls when eliding async and await. As a general rule, if the code does anything non-trivial, then you should keep the async and await. Only elide the async/await if the code is truly trivial - like in this case, when the delegate just binds employeeId on GetEmployeeAsync.

Related