The_Outsider
The_Outsider

Reputation: 176

Parallel Processing to Extract Data Using Revit API

As I understand, you are not supposed to use parallel processing to do stuff in Revit through its API. More information is available at http://thebuildingcoder.typepad.com/blog/2014/11/the-revit-api-is-never-ever-thread-safe.html

However, I am currently dealing with a problem of getting (and only getting) and then examining a lot of data to make some decisions. A sample code using TPL is given below, that seems to be working:

                Parallel.ForEach<Element>(allDocumentElementsNotVisibleInCurrentView,
                parallelOptions,
                element =>
                {
                    MyDerivedElement iaElement = new MyDerivedElement(uiDocument.Document, element, ElementStatusInView.Found); 

                    // The following condition line does the real heavy lifting and can be a lengthy process, involving data extraction from Revit, such as bounding boxes, geometry and curves
                    if (iaElement.IsContained(iaView))
                        lock (result)
                            result.Add(iaElement);
                });

So my question is, given that the above seems to work in tests, is it a good idea to let this one pass on parallel processing?

Thank you for your help!

Upvotes: 1

Views: 772

Answers (1)

Jeremy Tammik
Jeremy Tammik

Reputation: 8314

The Revit API cannot be used outside a valid Revit API context, and such a context is only provided by a Revit event notification to be processed within a Revit event handler. The most common event is the external command Execute method. In the past, this requirement was not strictly enforced. However, use of the Revit API outside a valid Revit API context can lead to a crash and data corruption. Read-only access may still work, but is risky. I certainly would not store the Element instance itself. Storing the ElementId seems like a safer bet. Please expect to crash at any time.

My recommendation would be to reduce the Revit API interaction and processing to an absolute minimimum, collect all the data required for processing, terminate the Revit API interaction after collecting the data, and then run the pure calculations with no further Revit API interaction in a separate thread or several threads at a later point after leaving the Revit API context.

Upvotes: 3

Related Questions