views:

65

answers:

2

Hi,

What's the best approach/pattern I should use for the following?

  1. Have a C# UI solution that will have (a) Winforms/WPF UI, and (b) class library.
  2. The UI will have to start a separate thread for the routine in the class library that will be polling
  3. The class library will then need to trigger a callback function in the UI to update UI fields if necessary

How do I best implement this callback arrangement so that the class library can be reused, and ideally it should have no dependency on the UI component.

thanks

+2  A: 

Use Backgroundworker for this. This will ease your implementation and thread management.

Kangkan
+2  A: 

You could do this via an Event being raised out of your library, this way the library will only need to pop the event, if the UI chooses to consume the event then that's implementation in the UI.

You could also expose a property eg CallbackMethod and have a delegate that it accepts, then in the UI you set the property to the addressof your function. When the library needs to "send the necessary callback" you check to see if the callback has been populated, then call the callback function (via the delegate) if it's been set, or just skip it if it hasn't

Paul Farry
I'm a big fan of events in order to promote loose coupling of objects, particularly in cases such as is described in the parent article. The problem with a callback is that the thread in this case would be tied to a particular interface in the calling thread, and less able to be changed independently. Having the thread trigger an event allows you to keep the thread object in the dark about everything else on the outside, and allows you to optionally provide a handler in the parent process. In essence this is largely the same as a callback, but I feel it's more elegant and self-contained.
S.Robins
I agree, events feel nicer overall and as long as you can work with the UI Invoking if the event has come from a thread you'll be fine, there are tricks to setup so that the thread can raise the event on the correct thread, but it is more trouble than it's worth for Internal libraries.I've had only 2 instances in my .net programming where I actually needed to use the Delegate/Call approach instead of events.
Paul Farry