3

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?

Sandy
  • 1,284
  • 2
  • 14
  • 32
  • I don't think there is any significant difference in this 2 snippets. Just use one that you like. – vasily.sib Mar 18 '20 at 03:35
  • The first generates another `IAsyncStatemachine` which is more *CIL*, and is an inefficient way of achieving no applicable difference – TheGeneral Mar 18 '20 at 03:57
  • Related: [At the end of an async method, should I return or await?](https://stackoverflow.com/questions/17886992/at-the-end-of-an-async-method-should-i-return-or-await) – Theodor Zoulias Mar 18 '20 at 20:52

1 Answers1

6

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.

FoxDeploy
  • 12,569
  • 2
  • 33
  • 48
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810