WPF线程和调度调用

本文关键字:调用 调度 线程 WPF | 更新日期: 2023-09-27 17:50:34

我在(*)行得到这个错误:

类型为'System '的未处理异常。额外信息:此API已被访问

奇怪的是它经过了这条线的上方。我的城市元素被加载在主窗口中。

有人有什么想法吗?

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

WPF线程和调度调用

所有UI对象只能在UI线程上添加和创建。

在你的情况下,你是在后台线程上创建DrawingVisual,并将其添加到UI线程的VisualCollection中。你应该在UI线程上创建DrawingVisual。

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

你是程序想要的另一个线程。

请检查以下文章,并测试您的代码