13

What is the working procedure of ISynchronizeInvoke?

How to work with it in C#?

SteveC
  • 15,808
  • 23
  • 102
  • 173
Jaswant Agarwal
  • 4,755
  • 9
  • 39
  • 49

2 Answers2

15

This basically describes a way to push work between threads; to push an item of work onto the other thread, use either Invoke (synchronous) or BeginInvoke (asynchronous - ideally calling EndInvoke later). Likewise, InvokeRequired is used to ask "do I need to do this? or can I execute the work myself?".

The most common use of this interface is in windows-forms, where it is part of how to push work onto the UI thread; you can of course use Control.Invoke / Control.BeginInvoke equally, but forms controls implement this interface to allow abstraction - so downstream code doesn't need to tie itself to windows forms. In the case of forms, InvokeRequired means "am I the UI thread?".

In reality, I'm not sure it is that common to use it directly. It is more common to handle events on the UI, and have the UI handle thread-switching using the most appropriate local mechanism.

Typical usage:

obj.Invoke((MethodInvoker) SomeMethod);

which executes (via a delegate) SomeMethod on the thread managed by obj (which implements the interface).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I have recently viewed a very easy implementation of `ISynchronizeInvoke` accompanied by a very simple `IAsyncResult` implementation: http://gurkashi.blogspot.com/2011/01/hi-all-in-this-post-i-will-demonstrate.html. Not to hi-jack the question, but I'm wondering if, now, with .Net 4.5 I can use async/await instead of the old-school pattern of BeginInvoke with callbacks. Even though the interface says `BeginInvoke`, *under the hood* I can implement from my 4.5 toolbox. – IAbstract Jun 13 '12 at 01:38
2

ISynchronizeInvoke Interface

The ISynchronizeInvoke interface provides synchronous and asynchronous communication between objects about the occurrence of an event. Objects that implement this interface can receive notification that an event has occurred, and they can respond to queries about the event. In this way, clients can ensure that one request has been processed before they submit a subsequent request that depends on completion of the first.

Also refer

http://blogs.msdn.com/jaredpar/archive/2008/01/07/isynchronizeinvoke-now.aspx

rahul
  • 184,426
  • 49
  • 232
  • 263