In order to avoid excessive memory leaks when coding for SharePoint 2010 I have used the following class:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
// 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 …
1,456 total views, no views today