WPF Dispatcher Invoke return value is always null

2019-04-07 18:40发布

问题:

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

However the return value of the Dispatcher invoke 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;
}

回答1:

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: The ThreadStart threw me off - this isn't multithreaded. What are you trying to accomplish with this code sample??



回答2:

It's because ThreadStart doesn't have a return type (void()).

Try this instead:

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


回答3:

The documentation for Dispatcher.Invoke states the return value is "The return value from the delegate being invoked or a null reference (Nothing in Visual Basic) if the delegate has no return value." Since the ThreadStart delegate you are using is void, you need to use a Func<T> or a custom delegate with a return value.