Search code examples
c#.netsharepointsharepoint-2007windows-sharepoint-services

Unexplained delay when assigning a string to an SPListItem field


I am using the SharePoint Object Model via a console app on the same server as the SharePoint installation, and using the following code:

SPSite MySite = new SPSite("http://server/");
SPWeb MyWeb = MySite.OpenWeb();
MyWeb.AllowUnsafeUpdates = true;
SPList MyList = MyWeb.Lists["Test"];

const string EmptyQuery = "0";
SPQuery q = new SPQuery { Query = EmptyQuery };

String Source = "Test String";

for( int i = 1; i < 1000; i++)
{
    Console.WriteLine("Creating new item");

    SPListItem MyItem = MyList.GetItems(q).Add();

    Console.WriteLine("Created new item");

    Console.WriteLine("Assigning Title Value");

    MyItem["Title"] = Source.ToString();

    Console.WriteLine("Assigned Title Value");

    MyItem.Update();
}

I am getting a several second pause between "Assigning Title Value" and "Assigned Title Value".

When I deploy the code as a Web Part, its instantaneous, the delay only seems to be when the code is deployed as a console application.

Edit: More information! When I have more than one field being assigned, its always the first field that is slow, any subsequent assignments are as fast as expected. If I switch the order of fields around, it has no effect on the delay - the first field is always slow.

Any thoughts?


Solution

  • It looks like this is because you're not accessing any fields before using the setter. If you read at least one field first, you'd probably see a slight delay there, and no delay on the setter, because under the hood SetValue() calls EnsureFieldCollection(), which - if the fields for the list item haven't already been populated - has to check back to the SPList's fields collection.

    Also, this is not in your code snippet, but make sure you are disposing of your SPWeb and SPSite objects when you're done. A good pattern is to use using:

    using(SPSite site = new SPSite("url"))
    {
        using(SPWeb web = site.OpenWeb())
        {
            //do stuff
        }
    }