«

»

May 20

SharePoint 2010 – Class to Hold ListItem Information

In order to avoid excessive memory leaks when coding for SharePoint 2010 I have used the following class:-

// Class to hold SPListItem information
public class SPListItemInfo
{
    public string WebUrl { get; set; }
    public Guid ListGuid { get; set; }
    public int ItemId { get; set; }

    public SPListItemInfo(SPListItem _item)
    {
        this.WebUrl = _item.Web.Url;
        this.ListGuid = _item.ParentList.ID;
        this.ItemId = _item.ID;
    }
}

private static void DoSomething(SPListItemInfo info)
{
    using (SPSite site = new SPSite(info.WebUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists[info.ListGuid];
            SPListItem item = list.GetItemById(info.ItemId);
            // ...
        }
    }
}

public static void DoSomethingNow(SPListItemInfo info)
{
    DoSomething(info);
}

public static void DoSomethingLater(object o)
{
    SPListItemInfo info = o as SPListItemInfo;
    if (info != null) // Ensure we have a valid SPListItemInfo object
    {
        Thread.Sleep(10000);
        DoSomething(info);
    }
}

SPListItem listitem;

// Use this to run code later on separate thread
SPListItemInfo info = new SPListItemInfo(listitem);
ParameterizedThreadStart pts = new ParameterizedThreadStart(DoSomethingLater);
Thread th = new Thread(pts);
th.Start(info);

// Use this to run code now
DoSomethingNow(info);

This avoids the need to parse the heavyweight SPWeb object between the routines. There is a slight overhead in re-creating the SPWeb objects when necessary, but this is outweighed by the ease of use.  The class and routines here can also be used to delay operations by running them on a separate thread.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>