user26242
user26242

Reputation: 93

Trouble updating UI using Dispatcher.Invoke

I am working on a plugin based WPF Application. The plugins are loaded parallely using multiple threads. One of the plugins is a UI plugin that uses a WPF RibbonWindow. I am trying to add a RibbonTab from Plugin A to the UI plugin.

Since the calling thread does not own the RibbonWindow, I am using the Dispatcher.Invoke on the RibbonWindow. Unfortunately the code inside the delegate is never being called. The application is still responsive, but the tab is not being added.

Is there anyway I can access the UI thread from another plugin? Can I have a thread that can be kept alive all through my application, for me to use that Thread for operating on the RibbonWindow?

 System.Threading.ThreadStart start = delegate()
        {
            log.Debug(Thread.CurrentThread.ManagedThreadId);

            if (!this.Dispatcher.CheckAccess())
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,  (ThreadStart)delegate() {
                    log.Debug(Thread.CurrentThread.ManagedThreadId);
                    ribbonRoot.Items.Add(myRibbonTab);
                });
            }
            else {
                log.Debug("We have access add directly.");
            }

        };

        new Thread(start).Start();

Please let me know if you need any additional information.

Thanks.

Upvotes: 0

Views: 1311

Answers (2)

ChrisWue
ChrisWue

Reputation: 19070

If you just want to add the ribbon tab you don't need to start a thread for it (you are already dispatching it to the UI thread) unless there is more you want to do on the thread. Even then it might be better to use the ThreadPool instead of creating a new thread. Any way, in scenarios like this I usually pass the Dispatcher from the main window to the plugin via the plugin interface instead of directly accessing the Application.Current.Dispatcher. Makes it more encapsulated and you have better control over it in unit tests.

Upvotes: 0

NightDweller
NightDweller

Reputation: 923

You need the Application.Current.Dispatcher to invoke it on the UI thread.

btw: Why are you casting to ThreadStart? (not important, just curious)

Upvotes: 1

Related Questions