I have several MeshGeometry3D elements that are stored in separate files. For example, somemodel.xml might contain <MeshGeometry3D ... />.
If I load them in the main UI thread, they lock up the UI while they load. So I’ve tried loading them in a separate thread:
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);
However, this gives an exception on the line viewportVisual.Geometry = geometry;: The calling thread cannot access this object because a different thread owns it.
In other words, the MeshGeometry3D was created on a different thread, so I cannot make it the Viewport2DVisual3D‘s Geometry.
I can’t figure out a way to asynchronously load the MeshGeometry3Ds without them being owned by the wrong thread. Is this just something that is not possible, or is there a way to do it?
Edit: Profiling suggests that about 13% of the time to load a MeshGeometry3D is spent loading the xml element from the file (var element = XElement.Load(filename);), and the rest is spent converting it to a 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),
};
So it doesn’t look like fetching the XML from disk is the bottleneck here.
Unless you need to modify the model later you can try to
Freezeit after it has been loaded, then it can be shared accross threads, see Freezable Objects Overview.