views:

15

answers:

1

I have an object that is updated from a polling loop on a thread. This object fires particular events when data changes, etc.

I'm trying to use this object in conjunction with a windows form, where I create event handlers on the form to update the UI. Of course, this causes cross-thread operation exceptions if I try to manipulate the UI directly in these handlers.

I can get it to work by going through the standard procedure of checking InvokeRequired, using a delegate, blah blah blah. But I want to publish this object as a library, and I don't want end-users to have to worry about all that.

I want my object to somehow take care of synchronizing those event callbacks with the form so that end-users can manipulate the UI elements in those handlers worry-free.

Is there a way to do this??

A: 

If your object is always related to a single form, there is a simple trick indeed. The important fact here is, that you instanciate your object from the thread you like to affect the form later.

The trick is to instanciate a simple Control (new Control()) in your object in the constructor. When you perform logic on your form, use the Invoke/BeginInvoke methods on this simple control, to dispatch the action to the correct calling thread. So you have the dispatching logic directly in your object and there is no need for other users of your object to take care about this.

JanW