The API doesn't officially support threading (see below) or a way to close an active document. That said, a work around to closing an active document is to call...
SendKeys.SendWait("^{F4}");
...from a separate thread. That works fine, except I need to loop through opening and closing several documents. If I put any code at all after thread, it will run it before closing the previous document. I have tried a number of standard threading callback methods including...
Task.Factory.StartNew(() =>
ThreadPool.QueueUserWorkItem(new WaitCallback
AutoResetEvent.WaitOne()
with no luck. And Thread.Sleep() just stalls the error/crash. Does anyone have any ideas.
"Revit's internals make use of multiprocessing in only a few select isolated locations. None of these locations currently encompass the code in the Revit API, or any part of it. Thus Autodesk does not recommend making any calls to the Revit API from within simultaneously executing parallel threads. It may be that some part of the Revit API is isolated enough to be able to execute successfully from within such threading code in a test environment; this should not be taken to be a guarantee that the same source code will function for any model or situation, or that a future change in Revit will not cause this code to cease to function."
public void OpenFile()
{
for (int i = 0; i < 3; i++)
{
uiApp.OpenAndActivateDocument(TargetPath(i));
ThreadPool.QueueUserWorkItem(CloseDocProc);
//any code here at all opens the next doc without closing the last
}
}
public void CloseDocProc(object stateInfo)
{
SendKeys.SendWait("^{F4}");
//can run code here
}