It is a well know thing, yet I run into this problem every now and then: SPWeb and SPSite objects are crashing when accessed from another thread.
Recently, I’ve had a problem at customer’s place that their application, “after minor changes”, just fell apart. They had a Windows Forms application, which imports raw text data into SharePoint. Now, while the import was running, UI was frozen, since everything was done in the UI thread – they didn’t know how much of the import was already done, progress bar was dead, they even didn’t know if it was finished.
Their developers have made some changes, and, correctly, moved all the import logic into it’s own thread. And there was a tricky part: everything fell apart.
From a very simple reason: they instantiated SPSite and SPWeb objects at the application start, used them in the all methods where they were needed, and disposed them at the end. It worked as a charm while everything was happening in one thread, at the moment they have introduced a new thread (for import) – it didn’t work anymore. How could it? SPSite and SPWeb are not thread safe, and it is clearly stated at MSDN that they are not:
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
The solution is really simple – instantiate SPSite and SPWeb in each thread where you need it. What the hence – instantiating itself is not that time consuming, instantiate it per-need with “using” keyword. And the threading problems are gone then.