Skip to main content
1 of 2
user avatar
user avatar

It's mostly likely because you already have an instance of the SPList (from another context) before you try to execute the deletion of an EventReceiver. That's why the ThreadAbortionException is thrown.

Instead of sending in the list, send its name instead and get the list inside the RunWithElevatedPrivileges codeblock.

private void RemoveEventReceiver(string listName, bool isRemove)
{
    if (isRemove) // No need to continue if it's FALSE
    {
        SPSecurity.RunWithElevatedPrivileges(() => 
        {
            using (var site = new SPSite(SPContext.Current.Site.ID))
            {
                using (var web = site.OpenWeb())
                {
                    // Get the list with elevated permissions
                    var list = web.Lists.TryGetList(listName);
                    
                    try
                    {
                        web.AllowUnsafeUpdates = true;

                        foreach (SPEventReceiverDefinition eventReceiver in list.EventReceivers)
                        {
                            if (receiver.Type == SPEventReceiverType.ItemUpdating)
                            {
                                eventReceiver.Delete();
                            }
                        }

                        // Update the list after the iteration is complete.
                        list.Update();
                    }
                    catch(Exception ex)
                    {
                        //...
                    }
                    finally 
                    {
                        // Remember to set AllowUnsafeUpdates to false again when you're done.
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }
        });
    }
}
user2536