i could not understand so could i get an exmaple of cached result and syncronous completion of async method.
following is the lines from
"If a method declared with the async modifier returns a cached result or completes synchronously"
i could not understand so could i get an exmaple of cached result and syncronous completion of async method.
following is the lines from
"If a method declared with the async modifier returns a cached result or completes synchronously"
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Tuhin PaulPosted Jul 3, 2025, 7:55 PM
First Call :
GetDataAsyncis called for the first time,_cachedResultisnull.Task.Delay(2000)), fetches the data, and stores it in_cachedResult.Second Call :
GetDataAsyncis called again,_cachedResultis no longernull.??????This pattern is commonly used in scenarios where expensive operations (e.g., database queries, API calls) can be optimized by caching results to avoid redundant work.
rajesh yadavPosted Jul 4, 2025, 4:40 AM
thnaku , unfortunatally i did not mention the return type, following is the situation whose code i needed?
When an asynchronous method returns a
Taskobject, performance bottlenecks might be introduced in certain paths. BecauseTaskis a reference type, aTaskobject is allocated from the heap. If a method declared with theasyncmodifier returns a cached result or completes synchronously, the extra allocations can accrue significant time costs in performance critical sections of code. This scenario can become costly when the allocations occur in tight loops.Tuhin PaulPosted Jul 3, 2025, 7:54 PM
Asynchronous Methods (
async) :asyncmodifier are typically used to perform operations that may take time to complete (e.g., I/O-bound or network-bound tasks).TaskorTaskto represent the ongoing operation.Cached Result :
Synchronous Completion :
async, it can complete synchronously if the work it needs to do is already done or doesn't require asynchronous operations.Combination :
asyncmethod might return a cached result or complete synchronously, which means it doesn't actually perform any asynchronous work. This can happen when the result is readily available.