docs icon indicating copy to clipboard operation
docs copied to clipboard

Bad await FromResult examples

Open olivier-net opened this issue 1 year ago • 1 comments

Type of issue

Missing information

Description

There are 2 places in the page where it does return await Task.FromResult(new User() { id = userId }); await and Task.FromResult are the opposite, the should not be use together.

Also, there are no example on what to do if the method is synchronous but must return a Task, ex: when implementing an interface.

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/async-scenarios

Content source URL

https://github.com/dotnet/docs/blob/main/docs/csharp/asynchronous-programming/async-scenarios.md

Document Version Independent Id

77bdee53-c2a0-e16f-c93a-3ca0afae0b93

Article author

@BillWagner

Metadata

  • ID: d885f1eb-2b37-693b-c91f-74b748c9424a
  • Service: dotnet-csharp
  • Sub-service: async-task-programming

Related Issues

olivier-net avatar Oct 16 '24 15:10 olivier-net

hi @olivier-net

This is an area that needs more work.

Short answers to your comments:

  • The Task.FromResult is the correct way to create a task when you need to return a completed task, possibly with a result, in a synchronous method. In general, Task.FromResult(true) is the typical pattern for a Task that doesn't include a result.
  • Yes, the only reason to use await Task.FromResult(...) is to force the compiler to generate the async state machine (because of the await). That shouldn't be used here.

BillWagner avatar Oct 17 '24 13:10 BillWagner