繁体   English   中英

Dispatcher.BeginInvoke(…)未调度任何内容

[英]Dispatcher.BeginInvoke(…) not dispatching anything

我试图从Web服务器上获取很多图像,所以为了不使服务器每秒过载数百个请求,我只允许其中一些通过WebService处理。 以下代码位于保存图像的对象以及所有绑定的位置。

ThreadStart thread = delegate()
{
    BitmapImage image = WebService.LoadImage(data);

    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
    {
        this.Image = image;
    }));
};

new Thread(thread).Start();

图像加载得很好,图像加载时UI流畅运行,但是this.Image = image永远不会被调用。 如果我使用Dispatcher.CurrentDispatcher.Invoke(..) ,则会调用该行,但不适用于设置Image。 调度员为什么不调用我的动作?

由于您是在辅助线程上创建BitmapImage ,因此它不属于WPF线程。 也许这段代码可以帮助您解决问题:

您发布的代码

ThreadStart thread = delegate()
{
    BitmapImage image = WebService.LoadImage(data, Dispatcher.CurrentDispatcher);

    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
    {
        this.Image = image;
    }));
};

new Thread(thread).Start();

如何更改WebService.LoadImage以使其“工作”

BitmapImage LoadImage(object data, Dispatcher dispatcher)
{
    // get the raw data from a webservice etc.
    byte[] imageData = GetFromWebserviceSomehow(data);

    BitmapImage image;

    // create the BitmapImage on the WPF thread (important!)
    dispatcher.Invoke(new Action(()=>
    {
        // this overload does not exist, I just want to show that
        // you have to create the BitmapImage on the corresponding thread
        image = new BitmapImage(imageData);
    }));

    return image;
}
System.Object
    |-> System.Windows.Threading.DispatcherObject
        |-> System.Windows.DependencyObject
            |-> System.Windows.Freezable
                |-> ... 
                    |-> System.Windows.Media.Imaging.BitmapImage

BitmapImage是线程关联的。 因此, this控件和BitmapImage对象应在同一线程中创建。 您也可以尝试仅冻结图像,但似乎无济于事。

BeginInvoke不会显示错误,因为它是由WPF处理的。 请参阅MSDN,如何设置WPF跟踪。

WPF是单线程的。 阅读所有员工描述的有关WPF的书。

暂无
暂无

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

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