Why is state parameter an object in various APIs? #110177
Replies: 2 comments 1 reply
-
It can avoid allocating additional closure object over existing state objects. For asynchronous calls, an allocation is unavoidable. In many cases, there is already an object holding enough information. |
Beta Was this translation helpful? Give feedback.
-
Many of these APIs including For example, here is an This does not explain why By the way, using the state parameter can save an allocation even if a tuple or other value type has to be boxed, since a lambda capturing a variable will result in one allocation for a DisplayClass object to hold the variable and another for the delegate. With the state parameter there is just the box to hold the state since the non-capturing lambda is shared. |
Beta Was this translation helpful? Give feedback.
-
A few methods that require delegates as one of their params also accept
state
parameter. Examples:One of the advantages of these overloads that contain
state
is the fact that they might help with avoiding allocations with closures. However, the fact that they're of typeobject
makes it impossible to avoid allocation when the thing being provided is not a reference type.Why aren't those overloads generic, allowing anything to be provided as
state
?For example, wouldn't it be beneficial for
OnStarting
to have the following shape:?
Beta Was this translation helpful? Give feedback.
All reactions