本文介绍了WPF线程和Dispather.Invoke的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在(*)行收到此错误:

I get this error at line (*):

奇怪的是,它经过了上面的行.我的城市元素像一个图像一样被加载到MainWindow.xaml中.

The curious thing is that it passes the line above this.My City element is loaded in MainWindow.xaml like an Image for examle.

有人有想法吗?

public class City : FrameworkElement
{
    VisualCollection _buildingsList;

    public City()
    {
        Thread t = new Thread(new ThreadStart(Draw));
        t.start();
    }

    private void Draw() 
    {
        DrawingVisual building = new DrawingVisual();

        // [...]

        Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
        {
            _buildingsList.Clear();
            _buildingsList.Add(building); // (*)
        }));
    }

    protected override Visual GetVisualChild(int index)
    {
        return _buildingsList[index];
    }

    protected override int VisualChildrenCount
    {
        get { return _buildingsList.Count; }
    }
}

推荐答案

应仅在UI线程上添加和创建所有UI对象.

在您的情况下,您正在在后台线程上创建DrawingVisual并将其添加到UI线程的VisualCollection中.您还应该在UI线程上创建DrawingVisual.

In your case you are creating DrawingVisual on background thread and adding it in VisualCollection on UI thread. You should create DrawingVisual also on UI thread.

Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
   DrawingVisual building = new DrawingVisual(); <-- Create on UI thread.
   _buildingsList.Clear();
   _buildingsList.Add(building);
}));

这篇关于WPF线程和Dispather.Invoke的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 01:53