raising events via "Invoke" - good pattern? - or not....

O

Oli

Hi - I am communicating with my UI thread using the following
technique. This has appalled one of my co-workers ;) - any comments
about it's brilliantness or lack thereof welcome.....

two threads:
1) UI thread
2) Worker thread

- something happens in the worker thread - I need to update the UI.
- worker thread exposes an event - UI thread wires an event handler
into that event
- when worker thread needs something to happen - it raises the event

*** but for the event handler to run on the UI thread - the worker
thread raises the event (via "Invoke") ***

I like this because the UI thread code needs to simply wire up an
event handler. There is hence good separation between the code running
the UI, and the code running the Worker thread.

O.
 
B

Brian Gideon

Hi - I am communicating with my UI thread using the following
technique. This has appalled one of my co-workers ;) - any comments
about it's brilliantness or lack thereof welcome.....

two threads:
1) UI thread
2) Worker thread

- something happens in the worker thread - I need to update the UI.
- worker thread exposes an event - UI thread wires an event handler
into that event
- when worker thread needs something to happen - it raises the event

*** but for the event handler to run on the UI thread - the worker
thread raises the event (via "Invoke") ***

I like this because the UI thread code needs to simply wire up an
event handler. There is hence good separation between the code running
the UI, and the code running the Worker thread.

O.

Hi,

I don't know why that would appall your coworker. It sounds similar
to the pattern Microsoft used with System.Timers.Timer and the
SynchronizingObject property.

Brian
 
S

Stoitcho Goutsev \(100\)

Oli,

I'd suggest to follow the design pattern of classes like
System.Timers.Timer. Those components have property called
SynchronizingObject of type ISynchronizeInvoke. If the user sets this
proeprty then the event raising code should use the sync object to invoke
the event handlers other wise ot raises the event handler directly. This way
the user can chose whether he/she wants to handle the event in the context
of the worker thread or the UI thread.
ISynchronizeInvoke is implemented by the Control class, so if the user
provides referenc to a control it basically works in the same way as you
call Control.Invoke, thus marshaling the event handler to the UI thread.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top