views:

44

answers:

2

I've got a bit of an issue here where I want to modify GUI elements from various worker threads. Until today, the method I was using worked, but it was most likely very incorrect.

The simplest case involves my plugin's GUI, which does something in a worker thread, and when that method completes its work, it calls my callback. That callback method is handled from the same thread, so it cannot do any GUI work. However, when my plugin's GUI is displayed by my main app GUI, my plugin GUI caches its Dispatcher reference -- when I do need to do GUI updates (or in this case, display a dialog), I call Dispatcher.Invoke(...).

Is there any inherent danger in setting the Dispatcher in my plugins like this?

Today, I have a new problem with this approach. My application needs to call that method in my plugin that launches the worker thread and displays a dialog. If I call the method before I open the plugin's GUI (which caches the Dispatcher reference), the operation will fail because the Dispatcher is null. I always check for that to make sure the app doesn't crash. However, now that the dialog isn't displayed, the necessary user interactions cannot proceed.

Can anyone suggest a better method for using the Dispatcher to ensure that I can display / modify a plugin's GUI elements from my main application? The only thing I can think of right now is to have my main application pass its Dispatcher reference to my plugin loader, add a "SetDispatcher" method to my plugin interface, and then have the plugin loader call this for every plugin that needs to be loaded.

A: 

If your plugin's GUI must exist by the time the background thread finishes, you should probably make sure that the plugin GUI creation/instantiation happens before you spin off that background process. That way, the plugin GUI element(s) Dispatcher is set by the framework before your async stuff finishes.

At a higher level (you may or may not be able to address this), it seems like you've got some inappropriate coupling between the GUI and the stuff that's occurring in the background.

FMM
A: 

For now, I've found that a nice solution, appropriate or not, is to export the main thread's Dispatcher via MEF, and then allow all of the plugins to import it. It seems like the cleanest way to deal with this sort of thing right now.

Dave