views:

487

answers:

3

I'm looking for articles, forum or blog posts dealing with SharePoint and thread safety? I'm quite sure there are some special aspects regarding thread safety that have to be considered when working with the SharePoint object model.

Actually I didn't find many information about this, yet.

So I'm looking forward to your answers.

Bye, Flo

+5  A: 

There are much worse pitfalls in the SharePoint OM than just plain old thread safety. Pay particular attention to working with objects retrieved from properties. You should always keep a pointer to an object while you work on it; example:

var list = web.List["MyList"]
list.Items[0]["Field1"] = "foo"
list.Items[0]["Field2"] = "bar"
list.Items[0].Update() // nothing is updated!

You might expect Field1 and Field2 to be updated by the final Update() call, but nope. Each time you use the indexer, a NEW reference to the SPListItem is returned.

Correct way:

SPListItem item = list.Items[0]
item["Field1"] = "foo"
item["Field2"] = "bar"
item.Update() // updated!

Just a start. Also google for pitfalls around the IDisposabe/Dispose pattern.

-Oisin

x0n
Not what I'm looking for but very interesting as well. I'll keep this in mind. Regarding the disposing issues with MOSS objects I've found a interesting article on MSDN: http://msdn.microsoft.com/en-us/library/aa973248.aspx
Flo
You're totally right but he's asking about thread safety.
Alex Angas
+2  A: 

There is one issue that I often run into: when writing your own list item receivers, you need to be aware of the fact that some of the events fire asynchronously, e.g. ItemAdded() which means your code could be running in multiple threads at the same time.

vitule
A: 

So after doing some more googling and searching on the web and testing, it seems as if you don't have to care about thread-safety that much when using the MOSS object model because you're always working with non-static and unique instances.

Furthermore an exception is thrown when a object e.g. a SPWeb was altered and saved by calling the Update() method before you saved your changes (also calling the Update() method) even though you got your object first.

In the following example the instruction web11.Update() will throw an exception telling you that the SPWeb represented through the object web12 was altered meanwhile.

SPSite siteCol1 = new SPSite("http://localhost");      

SPWeb web11 = siteCol1.OpenWeb();
SPWeb web12 = siteCol1.OpenWeb();                               

web12.Title = "web12";
web12.Update();

web11.Title = "web11";
web11.Update();

So the thready-safety seems to be handled by the object model itself. Of course you have to handle the exceptions that might be thrown due to race conditions.

Flo
Always make sure you are disposing your objects, use a using around your SPSites and SPWebs - http://msdn.microsoft.com/en-us/library/aa973248.aspx
Phill Duffy
Oh, you're definitely right. I left it out cause I was focused on the other issue.
Flo