BedrockFramework icon indicating copy to clipboard operation
BedrockFramework copied to clipboard

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

Open TheVeryStarlk opened this issue 11 months ago • 2 comments

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.

TheVeryStarlk avatar Mar 03 '24 18:03 TheVeryStarlk

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).

davidfowl avatar Mar 03 '24 18:03 davidfowl

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.

TheVeryStarlk avatar Mar 03 '24 19:03 TheVeryStarlk