views:

111

answers:

3

Hi,

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?

A: 

It may be a difference between Release and Debug builds, or the fact it has the debugger attatched. Try changing to a Release build, and if that doesn't work try running it without the debugger (Ctrl+F5 in Visual Studio)

ICR
Running without the debugger has no effect at all, same delay is experienced.
Moo
+5  A: 

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
    }
}
Rex M
A: 

First of all I would suggest making use of

using (SPSite MySite = new SPSite("http://server/"))
{
   using (SPWeb MyWeb = MySite.OpenWeb())
   {
      //do your stuff here
   }
}

You can check the EnsureFieldCollection by reading all the fields of the item before updating the field. If after that your first field is updated instantly you can be pretty sure that that is the reason.

KoenVosters
@KoenVosters: I'm pretty sure you don't need to read all of the fields, just one should suffice.
Alex Angas