While reviewing code last night I found this code. Of note, state
is captured via the lambda which executes the generic-typed callback action.
public static void Post<TState>(TState state, Action<TState> callback){
if(SynchronizationContext.Current is SynchronizationContext currentContext)
// Use capture-semantics for state
currentContext.Post(_ => callback(state), null);
else{
callback(state);
}
}
Post
however, natively supports pass-thru of state
, so the above can also be re-written like this...
public static void Post<TState>(TState state, Action<TState> callback){
if(SynchronizationContext.Current is SynchronizationContext currentContext)
// Use pass-thru state, not 'capture'
currentContext.Post(passedBackState => callback((TState)passedBackState), state);
else{
callback(state);
}
}
My question is simple... in this particular use-case where the callback is defined in the same scope as the state needing to be passed to it, is there any technical benefit and/or down-side to using capture-semantics (the first) over pass-thru (the second)? Personally I like the first because there's only one variable, but I'm asking about a technical difference, if any as both seem to work.