R – Sharepoint COMException 0x81020037

commultithreadingsharepoint

I am working on a SharePoint application that supports importing multiple documents in a single operation. I also have an ItemAdded event handler that performs some basic maintenance of the item metadata. This event fires for both imported documents and manually created ones. The final piece of the puzzle is a batch operation feature that I implemented to kick off a workflow and update another metadata field.

I am able to cause a COMException 0x81020037 by extracting the file data of a SPListItem. This file is just an InfoPath form/XML document. I am able to modify the XML and sucessfully push it back into the SPListItem. When I fire off the custom feature immediately afterwards and modify metadata, it occassionally causes the COM error.

The error message basically indicates that the file was modified by another thread. It would seem that the ItemAdded event is still writing the file back to the database while the custom feature is changing metadata. I have tried putting in delays and error catching loops to try to detect that the SPListItem is safe to modify with little success.

Is there a way to tell if another thread has a lock on a document?

Best Answer

Sometimes I see the ItemAdded or ItemUpdated firing twice for a single operation. You can try to put a breakpoint in the ItemAdded() method to confirm that.

The solution in my case was to single thread the ItemAdded() method:

private static object myLock = new object();
public override void ItemAdded(SPItemEventProperties properties) {
    if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(30))
    {
        //do your stuff here.
        System.Threading.Monitor.Exit(myLock);
    }
}
Related Topic