Explain the use of ISynchronizeInvoke in cross thread invocation in .NET?
+6
A:
It's just an interface which contains appropriate methods to:
- Check whether special handling is required (
InvokeRequired) - Invoke a delegate safely from a different thread, blocking until the action is completed (
Invoke) - Invoke a delegate safely from a different thread, returning immediately without blocking (
BeginInvokewhich can be coupled withEndInvoketo retrieve the result later)
The most commonly known implementation is Control in Windows Forms.
Basically the problem is that it's not safe to access UI elements within arbitrary threads. These mechanisms allow calls to be marshalled between threads relatively easily. By only tying yourself to ISynchronizeInvoke instead of Control, you can avoid business classes from being tightly coupled to the UI.
EDIT: Stephen's comment from below is worth repeating here:
It's important to note that
ISynchronizeInvokeis outdated. TheSynchronizationContextabstraction is more universal.Controlis not just the most commonly known implementation; it's the only Microsoft one.
Jon Skeet
2010-08-03 16:56:13
Thank you very much Jon! :)
NHans
2010-08-03 17:03:20
@NHans - Just a suggestion... If this helped out, accept the answer so that someone who looks at this later on will know what worked for you. It helps us all! :-) Cheers!
Buggabill
2010-08-03 17:22:18
It's important to note that `ISynchronizeInvoke` is *outdated*. The `SynchronizationContext` abstraction is more universal. `Control` is not just the most commonly known implementation; it's the *only* Microsoft one.
Stephen Cleary
2010-08-04 00:27:50
@Stephen: As of which version is ISynchronizeInvoke outdated? 4?
chiccodoro
2010-10-05 09:36:43
@chiccodoro: When I say "outdated", I don't mean that it's deprecated. I just mean that there's a better solution in `SynchronizationContext`, which was added in .NET 2.0. It's similar to `ISynchronizeInvoke`, but done in a way that also supports ASP.NET asynchronous pages. Then when WPF/Silverlight came along in .NET 3, they only supported `SynchronizationContext` and not `ISynchronizeInvoke`. So I would recommend using `SynchronizationContext` instead of `ISynchronizeInvoke` as far back as 2.0.
Stephen Cleary
2010-10-05 13:54:40