5

I found this code:

this.Invoke(new EventHandler(EventGetSum));

Is this not the same as writing:

EventGetSum();

What's the use of this?

Brann
  • 31,689
  • 32
  • 113
  • 162
Gold
  • 60,526
  • 100
  • 215
  • 315
  • That's a pretty bad title, maybe you should consider changing it to something more descriptive – grapefrukt Feb 27 '09 at 10:56
  • Check this question http://stackoverflow.com/questions/571706/shortest-way-to-write-a-thread-safe-access-method-to-a-windows-forms-control/571749#571749 – alex2k8 Feb 27 '09 at 10:51

3 Answers3

13

If you write EventGetSum() that immediately calls the EventGetSum method.

If you write new EventHandler(EventGetSum) that creates a delegate which will (in turn) call EventGetSum when it's invoked.

The call to Control.Invoke invokes the given delegate from the UI thread responsible for the control. This is necessary because you mustn't access UI elements from arbitrary threads.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

It executes the EventGetSum method in the thread to that the window this belongs to.

Timbo
  • 27,472
  • 11
  • 50
  • 75
4

This is normally used when dealing with cross thread UI calls.

Look at the MSDN documentation for ISynchronizeInvoke.

leppie
  • 115,091
  • 17
  • 196
  • 297