Search code examples
c#winformsanonymous-methodssynchronizationcontext

Is the state parameter useful when using a anonymous method in a callback?


I am using callbacks with the SynchronizationContext object to update client UIs from a WCF service.

The code pattern I use is the following:

public void SetResults(string callId, IEnumerable<Result> results)
{
    uiSyncContext.Post(new SendOrPostCallback(state => {
            var r = (IEnumerable<Result>)state;
            chart1.Series[callId].Points.DataBindXY(r.Select...
        }, results);
}

The Post method accepts a delegate, and a state object. There is no other signature.

Because I am using a anonymous method, it happens I tend to write:

public void SetResults(string callId, IEnumerable<Result> results)
{
    uiSyncContext.Post(new SendOrPostCallback(state => {
            chart1.Series[callId].Points.DataBindXY(results.Select...
        }, null);
}

Because:

  • It is shorter
  • It spares a cast
  • no needs to declare a local variable

Although it works, I am wondering what are the risks that the second approach could involve.

Is this considered as safe? Could the result parameter be "corrupted" somehow by subsequent calls?


Solution

  • Is this considered as safe?

    Yes. Because

    Could the result parameter be "corrupted" somehow by subsequents calls?

    No. results is local to the SetResults() method so although it is being captured it cannot be reused/intercepted elsewhere. All the code that can access it is visible here.

    Having said all that, I don't consider it much of an improvement over the first version.