For Sharepoint 2003 (SP2) I wrote an eventhandler wich assigns an unique number to a document when the INSERT event fires.
To avoid locking exceptions, the code loops until the file is no longer locked. Otherwise the document doesnt get a number.
This works OK, until someone locks a file, because all the other threads are waiting (with different documents) for the thread with the locked file.
I thought the threading mechanism for eventhandlers is parallel, but clearly it works like a stack.
How to avoid this? Do I have to write threading code?
Here's a snippet from the code:
try
{
System.Security.Principal.WindowsImpersonationContext wic = null;
wic = System.Security.Principal.WindowsIdentity.GetCurrent().Impersonate();
string _uniqueField = ReadSetting("RefUniqueField");
using (SPSite _site = new SPSite(EventInfo.Site.Url))
{
using (SPWeb _web = _site.OpenWeb())
{
System.Int64 _uniqueId = this.GetUniqueId();
bool _error = true;
int _nrOfTries = 0;
while (_error && (_nrOfTries <= 1800) )
{
_error = false;
_nrOfTries++;
try
{
SPFile _file = _web.GetFile(EventInfo.UrlAfter);
_file = _web.GetFile(EventInfo.UrlAfter);
Debug("processing file " + _file.Name);
SPListItem _item = _file.Item;
_item[_uniqueField] = _uniqueId;
_item.Update();
}
catch (Exception e)
{
EventLog.WriteEntry(_source, e.Message + "\n" + e.StackTrace,EventLogEntryType.Error);
_error = true;
Thread.Sleep(1000);
}
}
}
wic.Undo();
}
}
catch (Exception e)
{
EventLog.WriteEntry(_source + " ", e.Message + "\n" + e.StackTrace, EventLogEntryType.Error);
}
To avoid locking exceptions, the code loops until the file is no longer locked. Otherwise the document doesnt get a number.
This works OK, until someone locks a file, because all the other threads are waiting (with different documents) for the thread with the locked file.
I thought the threading mechanism for eventhandlers is parallel, but clearly it works like a stack.
How to avoid this? Do I have to write threading code?
Here's a snippet from the code:
try
{
System.Security.Principal.WindowsImpersonationContext wic = null;
wic = System.Security.Principal.WindowsIdentity.GetCurrent().Impersonate();
string _uniqueField = ReadSetting("RefUniqueField");
using (SPSite _site = new SPSite(EventInfo.Site.Url))
{
using (SPWeb _web = _site.OpenWeb())
{
System.Int64 _uniqueId = this.GetUniqueId();
bool _error = true;
int _nrOfTries = 0;
while (_error && (_nrOfTries <= 1800) )
{
_error = false;
_nrOfTries++;
try
{
SPFile _file = _web.GetFile(EventInfo.UrlAfter);
_file = _web.GetFile(EventInfo.UrlAfter);
Debug("processing file " + _file.Name);
SPListItem _item = _file.Item;
_item[_uniqueField] = _uniqueId;
_item.Update();
}
catch (Exception e)
{
EventLog.WriteEntry(_source, e.Message + "\n" + e.StackTrace,EventLogEntryType.Error);
_error = true;
Thread.Sleep(1000);
}
}
}
wic.Undo();
}
}
catch (Exception e)
{
EventLog.WriteEntry(_source + " ", e.Message + "\n" + e.StackTrace, EventLogEntryType.Error);
}