WPF Dispatcher return value is always null

I have a method call that returns a UIElement that I call using Dispatcher , below is the code.

However, the return value of the Dispatcher call is always NULL, any ideas?

 void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { var slides = (IList<UIElement>)e.Argument; var bmpSlides = new List<UIElement>(); var imageService = new ImageService(); int count = 0; foreach (UIElement slide in slides) { object retVal = slide.Dispatcher.Invoke( new ThreadStart(() => imageService.GenerateProxyImage(slide))); bmpSlides.Add(imageService.GenerateProxyImage(slide)); _backgroundWorker.ReportProgress(count / 100 * slides.Count); count++; } e.Result = bmpSlides; } 
+6
c # backgroundworker wpf dispatcher
source share
3 answers

D'oh, here's how to do what you are trying to do:

 object retVal; slide.Dispatcher.Invoke(new Action(() => retval = imageService.GenerateProxyImage(slide))); 

Edit: ThreadStart threw me away - this is not multithreading. What are you trying to accomplish with this sample code?

+7
source share

This is because ThreadStart does not have a return type ( void() ).

Try this instead:

 UIElement retVal = slide.Dispatcher.Invoke(new Func<UIElement>( () => imageService.GenerateProxyImage(slide))); 
+7
source share

The documentation for Dispatcher.Invoke indicates that the return value is "The return value from the called delegate, or Nothing in Visual Basic if the delegate does not have a return value." Since the ThreadStart delegate you are using is not valid, you need to use Func<T> or a custom delegate with a return value.

+1
source share

All Articles