Unable to delete blocks in some layers


I am a computer engineer but a newbie in using Rhino 7 in C#.

I am working on a plug-in in C# with Rhino 7. I would like to delete all layers of a hierarchy starting with one specific layer. But when I try to delete the blocks included in the layers, I sometimes get a message about the block that was not being deleted. Then the layer cannot be deleted either.

What should I do to be able to delete all blocks and then delete the layer ? I do not worry about keeping any of the blocks contained in the layers. Thank you for your help.

The C# code I use to delete the blocks is the following :

 private static void ClearAllBlockInstancesFromLayer(Layer layer, RhinoDoc document)

        var objs = document.Objects.FindByLayer(layer).OfType<InstanceObject>();

        foreach (var obj in objs)
            obj.Explode(true, out _, out _, out _);
            var d = document.InstanceDefinitions.FindId(obj.Id);
            if (d != null)