1

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?

Larry
  • 17,605
  • 9
  • 77
  • 106

1 Answers1

2

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • If there is only one parameter, sure it is not much of an improvement. Hovewer, some callbacks passes many more parameters, and it is very handy for me to use them directly in the anonymous function body. – Larry Oct 16 '14 at 12:23
  • If those callbacks are forced on you then yes, it might help. But it is exactly what made you ask this question that speaks against it. – H H Oct 16 '14 at 12:51