如何在单独的线程中加载多个3D几何图形而不会遇到线程所有权问题?
我有几个MeshGeometry3D
元素存储在单独的文件中。 例如, somemodel.xml
可能包含 。
如果我在主UI线程中加载它们,它们会在加载时锁定UI。 所以我尝试在一个单独的线程中加载它们:
ThreadStart threadStart = delegate { var geometry = ConvertXmlFileToMeshGeometry3D(filename); viewport2DVisual3D.Dispatcher.BeginInvoke( DispatcherPriority.Normal, new Action(delegate { viewport2DVisual3D.Geometry = geometry; })); }; threadStart.BeginInvoke(delegate(IAsyncResult aysncResult) { threadStart.EndInvoke(aysncResult); }, null);
但是,这在行viewportVisual.Geometry = geometry;
上给出了一个例外viewportVisual.Geometry = geometry;
: The calling thread cannot access this object because a different thread owns it.
换句话说, MeshGeometry3D
是在不同的线程上创建的,所以我不能把它变成Viewport2DVisual3D
的Geometry。
我无法想出一种方法来异步加载MeshGeometry3D
而不会被错误的线程拥有。 这只是不可能的事情,还是有办法做到的?
编辑:分析表明加载MeshGeometry3D
大约13%的时间用于从文件中加载xml元素( var element = XElement.Load(filename);
),其余的用于将其转换为MeshGeometry3D:
return new MeshGeometry3D { Normals = (Vector3DCollection)new Vector3DCollectionConverter().ConvertFromString(element.Attribute("Normals").Value), Positions = (Point3DCollection)new Point3DCollectionConverter().ConvertFromString(element.Attribute("Positions").Value), TextureCoordinates = (PointCollection)new PointCollectionConverter().ConvertFromString(element.Attribute("TextureCoordinates").Value), TriangleIndices = (Int32Collection)new Int32CollectionConverter().ConvertFromString(element.Attribute("TriangleIndices").Value), };
因此,从磁盘中获取XML看起来并不像是瓶颈。
除非您以后需要修改模型,否则可以在加载后尝试Freeze
它,然后可以跨线程共享它,请参阅Freezable Objects Overview 。
上述就是C#学习教程:如何在单独的线程中加载多个3D几何图形而不会遇到线程所有权问题?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1026140.html