davidfowl / BedrockFramework

High performance, low level networking APIs for building custom servers and clients.
MIT License
1.05k stars 153 forks source link

Question about using some code piece in `Server.cs` #169

Open TheVeryStarlk opened 8 months ago

TheVeryStarlk commented 8 months ago

for each connection a running listener instance gets it calls an execute connection method and does not await it, and that method's first line is an awaited task yield method. So my question is, what is the reason behind doing this instead of just calling Task.Run and passing the connection delegate's method.

davidfowl commented 8 months ago

Avoids closure allocations. Using Task.Yield when there's no sync context will re-queue the existing async state machine to the thread pool.

There's 0 allocations when you do it this way. When you use Task.Run there's a new Task allocation, a delegate allocation and a closure allocation (because there's state that would be captured here).

TheVeryStarlk commented 8 months ago

Makes sense. Thank you for this response. I asked this because I had similar code where I used Task.Run, I will refactor it to how it is done in Bedrock.