Opening & closing of multiple models in background while completing a set of tasks

I did some changes and it is working now!

I set the line:

	newfilepath = newpath + "\\" + filenames

To:

	newfilepath = newpath + "\\" + str(filenames)

And removed two flatten nodes, leaving as this:

However, it seems that the files are not being closed, even with the line

	newdoc.Close(True)

As I can see them in the worksharing monitor and the memory is still in use.

The current script is now:

import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
from Autodesk.Revit.Attributes import*

import clr
clr.AddReference("RevitAPIUI")
from  Autodesk.Revit.UI import *

# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

from System.Collections.Generic import *

# Import Revit Nodes
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.ImportExtensions(Revit.GeometryConversion)

# Import python library
import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)
import os

tOptions = TransactWithCentralOptions()

doc = DocumentManager.Instance.CurrentDBDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
app = uiapp.Application
uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument

def flatten(*args):
for x in args:
    if hasattr(x, '__iter__'):
        for y in flatten(*x): yield y
    else: yield x


#Credits Archi-lab
def checkParameter(param):
for p in param:
	internal = p.Definition
	if internal.BuiltInParameter != BuiltInParameter.INVALID:
		return p
return param[0]

def GetParaValue(params):
paravalue = []
p = checkParameter(params)
if p.StorageType == StorageType.String:
	paravalue.append(p.AsString())
elif p.StorageType == StorageType.ElementId:
	paravalue.append(p.AsValueString())
elif p.StorageType == StorageType.Integer:
	paravalue.append(p.AsValueString())
else:
	paravalue.append(None)
return paravalue

if isinstance(IN[0], list):
file = IN[0]
filename = IN[2]
else:
file = [IN[0]]
filename = [IN[2]]

newpath = IN[1]
LinkNames, newdocpath, results, unloadstatus, linkParas = [], [], [], [], []

openConfig = WorksetConfiguration(WorksetConfigurationOption.CloseAllWorksets)
oOptions = OpenOptions()
oOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets
oOptions.Audit = True
oOptions.SetOpenWorksetsConfiguration(openConfig)

worksharingOptions = WorksharingSaveAsOptions()
worksharingOptions.SaveAsCentral = True

SaveOptions = SaveAsOptions()
SaveOptions.MaximumBackups = 50
SaveOptions.SetWorksharingOptions(worksharingOptions)
SaveOptions.OverwriteExistingFile = True

rOptions = RelinquishOptions(False)
rOptions.StandardWorksets = True
rOptions.ViewWorksets = True
rOptions.FamilyWorksets = True
rOptions.UserWorksets = True
rOptions.CheckedOutElements = True

sOptions = SynchronizeWithCentralOptions()
sOptions.SetRelinquishOptions(rOptions)
sOptions.Compact = True
sOptions.SaveLocalBefore = True
sOptions.SaveLocalAfter = True

TransactionManager.Instance.ForceCloseTransaction()

try:
for files,filenames in zip(file,filename):
	modelpath = FilePath(files)
	newdoc = app.OpenDocumentFile(modelpath,oOptions)
	collector = Autodesk.Revit.DB.FilteredElementCollector(newdoc)
	linkTypes = UnwrapElement(collector.OfClass(Autodesk.Revit.DB.RevitLinkType))
	for linkType in flatten(linkTypes):
		linkPara = linkType.GetParameters("Type Name")
		linkParavalue = GetParaValue(linkPara)
		try:
			linkType.Unload(None)
			unloadstatus.append(True)
		except:
			unloadstatus.append(False)
		results = [unloadstatus]		
	newfilepath = newpath + "\\" + str(filenames)
	newdoc.SaveAs(newfilepath,SaveOptions)			
	newdoc.SynchronizeWithCentral(tOptions,sOptions)
	newdoc.Close(True)
	newdocpath.append(newfilepath) 
	OUT = newdocpath 	
except Exception,e:
OUT = str(e)