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

本文关键字:调度 任何内 BeginInvoke Dispatcher | 更新日期: 2023-09-27 17:49:46

我正试图从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(..),则调用该行,但不适用于设置图像。为什么调度员不调用我的操作?

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

由于您在工作线程上创建了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的书,其中所有员工都描述了这一点。