简体   繁体   English

WPF Dispatcher Invoke返回值始终为null

[英]WPF Dispatcher Invoke return value is always null

I have a call to a method that returns a UIElement that I call using the Dispatcher , below is the code. 我有一个方法的调用,该方法返回使用Dispatcher调用的UIElement ,下面是代码。

However the return value of the Dispatcher invoke is always NULL, any ideas? 但是Dispatcher调用的返回值始终为NULL,有什么想法吗?

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;
}

It's because ThreadStart doesn't have a return type ( void() ). 这是因为ThreadStart没有返回类型( void() )。

Try this instead: 尝试以下方法:

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

D'oh, here's how to do what you are trying to do: D'oh,这是您要执行的操作:

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

Edit: The ThreadStart threw me off - this isn't multithreaded. 编辑: ThreadStart让我失望-这不是多线程的。 What are you trying to accomplish with this code sample?? 您试图用此代码示例完成什么?

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." Dispatcher.Invoke文档指出返回值是“正在调用的委托的返回值,或者如果委托没有返回值,则为null引用(在Visual Basic中为Nothing)”。 Since the ThreadStart delegate you are using is void, you need to use a Func<T> or a custom delegate with a return value. 由于您使用的ThreadStart委托无效,因此您需要使用Func<T>或具有返回值的自定义委托。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM