Search code examples
c#task-parallel-librarypolly

What is the correct way to call Polly ExecuteAsync method?


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?


Solution

  • 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 omiting or leaving out async and await. As a general rule, if the code does anything non-trivial, then you should keep the async and await.

    Only elide(leave-out) the async/await if the code is truly trivial - like in this case, when the delegate just binds employeeId on GetEmployeeAsync.