DEV Community

Discussion on: C# and .NET Core Appreciation Post. The most beautiful piece of code I have ever seen... this month!

Collapse
 
fcastells profile image
Francesc Castells

Drop the async and await keywords for better performance.

Collapse
 
sduduzog profile image
Sdu

At some point, I'm looking forward to benchmarking the alternatives i.e. Fluent vs Lambda, Async vs Sync. I'm certain there's no one answer for every use case

Thread Thread
 
vegardst1 profile image
zend

Fluent translates to the same underlying Linq statements and concequently the same generated SQL. Note: The await keyword can be used in front of the parentheses.

Async code frees up the thread to do other things while it's waiting for the slower database network roundtrip. You are trading a small setup cost for starting the state machine handling the async processing, but that's it.

Thread Thread
 
sduduzog profile image
Sdu

So basically async statements are useful for performance in situations where the data being processed is rather large

Thread Thread
 
fcastells profile image
Francesc Castells

I agree that using the Async flavor of the SingleOrDefault is generally the preferred way as it improves massively the amount of load a single server can absorb. My comment was simply that the proposed method does not need to be async (contain the keyword async in the signature) as there is no need to await tasks and execute continuations within the function. So, basically, you can directly return the Task returned by SingleOrDefaultAsync without awaiting it as the caller will await it.

Thread Thread
 
illuminatecode profile image
illumiNateCode

@Beautus S Gumede on "So basically async statements are useful for performance in situations where the data being processed is rather large"

(Not seeing proper "Reply" function on mobile)

That's one example where async is advantageous, and there are many, and it gets complicated pretty quick. I would recomend doing a deep dive on Asynchronous and Threading, but know that they are two very different subjects (although their impacts on your code can appear similar).

There's a pretty common analogy used to explain threading involving a chef/cook that I find to be a good foundation for internalizing the concept. Examples are all over Google for that. This article gives you a reasonable overview with some good detail, IMO: medium.com/swift-india/concurrency...

Happy coding!

Thread Thread
 
cmoya212b profile image
cmoya212b

@Beautus S Gumede In a highly performant scalable web app, async/await allows .NET to momentarily give the underlying thread to a different incoming request while waiting on IO (such as a database call). It makes .NET prolly the most scalable stack out there when done right. NodeJS does similar things with its singlethreaded event loop.