views:

539

answers:

2

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?

+1  A: 

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);
    }
}
vitule
A: 

@vitule

I'll have to look into that and get back to you. The problem on my end seems to be that there is code running in a different class, in a different feature, being controlled by a different thread, all of which are trying to access the same record.

I am trying to avoid using a fixed delay. With any threading issue, there is the pathological possibility that one thread can delay or block beyond what we expect. With deployments on different server hardware with different loads, this is a very real possibility. On the other end of the spectrum, even if I were to go with a delay, I don't want it to be very high, especially not 30 seconds. My client will be importing tens of thousands of documents, and a delay of any significant length will cause the import to take literally all day.

Jason Z