Revit 2025.4 crashes when using FilteredElementCollector

Hi All,

Getting this error “System.AccessViolationException: ‘Attempted to read or write protected memory. This is often an indication that other memory is corrupt.’

If I use below method in Addin
**FilteredElementCollector(
Document hostDocument,
ElementId viewId,
ElementId linkId
)
**
If I run the same class using Addin Manager its perfectly working fine. But while running the same directly using Addin its prompting error

Are you able to provide more context? Is this a Dynamo question or is it more appropriate for the Autodesk Revit API Forum?

Its related to Revit API forum, where someone already raised the same concern but still unresolved

As @Mike.Buttery indicated most (99.9%) of all Dynamo users aren’t apt to be able to help here, so the Revit API forum is more appropriate. When you posted there did you provide a full code sample showing the issue? Can you provide a link so I can ask one of my colleagues to take a look?

Hi @jacob.small , Thank you for your proactive response. Hereby I’m sharing the post link and full code for your reference

Facing error in the below method

var elmns = new FilteredElementCollector(doc, choosenView.Id, revitLinkInstance.Id)
.OfClass(typeof(Pipe))
.Cast()
.ToList();
"

Revit 2025.4 crashes when using FilteredElementCollector - Autodesk Community

public class SprinklerPipeTagging : IExternalCommand
{
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        UIDocument uidoc = commandData.Application.ActiveUIDocument;
        Document doc = uidoc.Document;



        //All Views in Project
        var allViews_Total = new FilteredElementCollector(doc)
                            .OfClass(typeof(Autodesk.Revit.DB.View))
                            .Cast<Autodesk.Revit.DB.View>()
                            .Where(v => v.ViewType == ViewType.AreaPlan)
                            .OrderBy(v => v.Name)
                            .ToList();


        List<View> allViews = new List<View>();

        foreach (View view in allViews_Total)
        {
            if (view.Name.Contains("(UNDER SLAB)")) { allViews.Add(view); }

        }


        List<Element> allAreas = (List<Element>)new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Areas).ToElements();



        List<Autodesk.Revit.DB.View> selectedViews = new List<Autodesk.Revit.DB.View>();
        //List<Area> selectedAreas = new List<Area>();


        #region View Selection

        try
        {

            // Pass both name + ElementId
            var viewData = allViews.Select(v => (v.Name, v.Id.IntegerValue)).ToList();

            var (selected, indices) = InputSelectionWindow.GetUserSelection(viewData);


            var selViews = indices.Select(i => allViews[i]).ToList();
            selectedViews.AddRange(selViews);

        }
        catch (System.Exception ex)
        {
            message = ex.Message;
            return Result.Failed;
        }
        #endregion



        #region link selection

        //// Collect Revit link instances
        //List<RevitLinkInstance> links = new FilteredElementCollector(doc)
        //    .OfClass(typeof(RevitLinkInstance))
        //    .Cast<RevitLinkInstance>()
        //    .ToList();

        //RevitLinkInstance revitLinkInstance = null;

        //using (SelectRevitLinkForm form = new(links))
        //{
        //    if (form.ShowDialog() == DialogResult.OK && form.SelectedLink != null)
        //    {
        //        //SelectRevitLinkForm forms = new SelectRevitLinkForm(links);
        //        revitLinkInstance = form.SelectedLink;
        //        Document linkDoc = revitLinkInstance.GetLinkDocument();
        //    }
        //}

        #endregion

        List<RevitLinkInstance> links = new FilteredElementCollector(doc)
            .OfClass(typeof(RevitLinkInstance))
            .Cast<RevitLinkInstance>()
            .ToList();

        RevitLinkInstance revitLinkInstance = null;


        foreach (RevitLinkInstance rvtLink in links)
        {
            string linkName = rvtLink.Name;
            if (linkName.Contains("-FPR-")) { revitLinkInstance = rvtLink; }
        }


        Transform linkTransform = revitLinkInstance.GetTotalTransform();


        List<Pipe> skPipes = new List<Pipe>();
        List<List<IndependentTag>> tagsList = new List<List<IndependentTag>>();

        using (TransactionGroup tgs = new TransactionGroup(doc, "Fire Pipes Tagging"))
        {
            tgs.Start();


            for (int i = 0; i < selectedViews.Count; i++)
            {
                Area area = null;
                Autodesk.Revit.DB.View choosenView = selectedViews[i];
                //Autodesk.Revit.DB.View choosenView = doc.ActiveView;



                string viewName = choosenView.Name;
                string falseText = " (UNDER SLAB)";
                string planName = viewName.Replace(falseText, "");

                foreach (Element areaElm in allAreas)
                {
                    string areaName = areaElm.LookupParameter("ROOM - LOD Code").AsValueString();

                    if (areaName != null)
                    {
                        if (viewName.Contains(areaName))
                        {
                            area = areaElm as Area;
                        }
                    }
                }





                if (area != null && choosenView != null)
                {
                    //FilteredElementCollector fec = new FilteredElementCollector(doc, choosenView.Id, revitLinkInstance.Id);
                    //List<Element> elmns = new List<Element>(fec.WhereElementIsNotElementType().ToElements());


                    var elmns = new FilteredElementCollector(doc, choosenView.Id, revitLinkInstance.Id)
                        .OfClass(typeof(Pipe))
                        .Cast<Pipe>()
                        .ToList();


                    //var elmns = CollectAllVisiblePipes(revitLinkInstance, choosenView);


                    List<Pipe> pipes = new List<Pipe>();


                    foreach (Pipe elm in elmns)
                    {
                        string categName = elm.Category.Name;

                        if (categName == "Pipes")
                        {
                            Pipe pi = elm as Pipe;

                            LocationCurve locCrv = pi.Location as LocationCurve;
                            Line line = locCrv.Curve as Line;
                            XYZ direction = line.Direction;

                            double vectX = Math.Round(direction.X);
                            double vectY = Math.Round(direction.Y);
                            double vectZ = Math.Round(direction.Z);


                            if (vectX != 0 || vectY != 0)
                            {
                                pipes.Add(pi);
                            }
                            else if (vectZ == 0)
                            {
                                pipes.Add(pi);
                            }
                        }
                    }



                    if (pipes.Count > 0)
                    {


                        double tagOffset = 200 / 304.8;
                        List<Reference> pipeRefs = new List<Reference>();
                        List<XYZ> midPoints = new List<XYZ>();
                        List<bool> horizontal = new List<bool>();


                        foreach (Pipe pipe in pipes)
                        {
                            LocationCurve locCrv = pipe.Location as LocationCurve;
                            Line crv = locCrv.Curve as Line;
                            XYZ pt = crv.Evaluate(0.5, true);

                            double crvLength = crv.Length * 304.8;

                            XYZ crvDirection = crv.Direction;
                            double vectX = Math.Round(crvDirection.X);

                            bool pointExists = false;

                            if (area != null && pt != null)
                            {
                                bool result = CheckPointInRoom.IsPointInsideRoom(area, pt);

                                if (result) { pointExists = true; }


                                if (crvLength > 300 && pointExists)
                                {

                                    //Transfrom point to Link Point
                                    XYZ hostPt = linkTransform.OfPoint(pt);

                                    Reference pipeR = new Reference(pipe as Element);
                                    Reference pipeRef = pipeR.CreateLinkReference(revitLinkInstance);

                                    if (vectX != 0)
                                    {
                                        pipeRefs.Add(pipeRef);
                                        horizontal.Add(true);
                                        XYZ newPt = new XYZ(hostPt.X, (hostPt.Y + tagOffset), hostPt.Z);
                                        //XYZ newPt = hostPt;
                                        midPoints.Add(newPt);
                                    }
                                    else
                                    {
                                        pipeRefs.Add(pipeRef);
                                        horizontal.Add(false);
                                        XYZ newPt = new XYZ((hostPt.X - tagOffset), hostPt.Y, hostPt.Z);
                                        //XYZ newPt = hostPt;
                                        midPoints.Add(newPt);
                                    }
                                }
                            }

                        }

                        //Output Tags
                        List<IndependentTag> newTags = new List<IndependentTag>();


                        using (TransactionGroup tg = new TransactionGroup(doc, "Fire Pipe Tags"))
                        {
                            tg.Start();

                            for (int ii = 0; ii < pipeRefs.Count; ii++)
                            {
                                if ((pipeRefs[ii] != null) && (midPoints[ii] != null))
                                {


                                    IndependentTag tag = CreateNewTag(doc, choosenView, pipeRefs[ii], horizontal[ii], midPoints[ii]);

                                    newTags.Add(tag);
                                }

                            }
                            tg.Assimilate();
                        }

                        tagsList.Add(newTags);

                    }


                    else
                    {
                        Autodesk.Revit.UI.TaskDialog.Show("Failed", $"This view cant be Tagged: {choosenView.Name.ToString()}");
                    }

                }

                else
                {
                    Autodesk.Revit.UI.TaskDialog.Show("Failed", "No Tags Created");
                    return Result.Cancelled;
                }


            }


            if (tagsList.Count == 0)
            {
                Autodesk.Revit.UI.TaskDialog.Show("Failed", "No Tags Created");
                return Result.Cancelled;
            }
            else { Autodesk.Revit.UI.TaskDialog.Show("Success", $"No. of Views Tagged: {tagsList.Count.ToString()}"); }


            tgs.Assimilate();
            
        }

        return Result.Succeeded;

    }


    public static IndependentTag CreateNewTag(Document doc, Autodesk.Revit.DB.View view, Reference reference, bool orientation, XYZ point)
    {
        IndependentTag createdTag = null;

        using (Transaction t = new Transaction(doc, "Sprinkler Pipe Tag"))
        {
            t.Start();

            if (orientation)
            {
                IndependentTag tag = IndependentTag.Create(doc, view.Id, reference, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Horizontal, point);
                createdTag = tag;
            }
            else
            {
                IndependentTag tag = IndependentTag.Create(doc, view.Id, reference, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.Vertical, point);
                createdTag = tag;
            }

            t.Commit();

        }

        return createdTag;

    }

First thing I would try is setting a break point here, and look at what the collector returns:

List<RevitLinkInstance> links = new FilteredElementCollector(doc)
            .OfClass(typeof(RevitLinkInstance))
            .Cast<RevitLinkInstance>()
            .ToList();

Confirm you only see the few link instances you would expect and no types or templates or other object types have snuck in.

Next check what object you have in memory when you get to the failing collector. Is it actually the link you expect, or something else?

Its responding a RevitLinkInstance as expected,
& even
var elmns = new FilteredElementCollector(doc, choosenView.Id, revitLinkInstance.Id)
.OfClass(typeof(Pipe))
.Cast()
.ToList();

this method is working perfectly if I run the same class using Addin Manager.

I’m facing this error only if I run the command in debug mode or if I run the same command after releasing the addin. Attached the video for your reference

This is why I’m thinking the larger add-in is doing something with documents that I am not yet seeing. But if you’re getting valid results as you step though the debugger until you hit the limit, it may be that you’re just utilizing more memory than you should, and have to step back into a reduced scope or re-architect something elsewhere in the code.

The FilteredElementCollector works fine, but when I perform some actions using it, a System.AccessViolationException error occurs. Is there any alternative solution for this?

Attached the video for reference

Sadly no ideas here - likely best to provide the data you’ve been given here (the code and this recording) back to the Revit API forum so that the developers have a chance to look at it.

Thank you. Will share the same in Revit API forum

The issue has been resolved after using the Dispose() method

2 Likes

Did you find this or is there an explanation on the Revit API forum?
Would be interested in reading the discussion if there is one :slight_smile:

I have figured out the solution, myself & someone else as well raised the same concern in Revit API forum, but no response yet. My issue got resolved after using Dispose, there might be alternate solutions as well, which we will get to know from Professionals