Skip to content

Instantly share code, notes, and snippets.

@kamsar
Created October 29, 2013 02:02
Show Gist options
  • Save kamsar/7208043 to your computer and use it in GitHub Desktop.
Save kamsar/7208043 to your computer and use it in GitHub Desktop.
Demonstration of using async to grab a bunch of Sitecore queries in parallel Performance on a dual-core machine appeared to be 30-100% faster than iterative.
using System.Linq;
using Isite.Sitecore.UI.WebControls;
using Isite.Extensions;
using System.Web.UI;
using System.Threading.Tasks;
using Sitecore.Data.Items;
using System.Collections.Generic;
using System.Threading;
using Sitecore.Caching;
using System.Diagnostics;
namespace AsyncTest
{
public class AsyncTest : WebControl
{
private List<Item[]> _taskResults = new List<Item[]>();
protected override void OnLoad(System.EventArgs e)
{
// the RegisterAsyncTask() method allows us to register something to run asynchronously
// from an event handler that would otherwise have to be async void (which is EVIL)
// This task will begin executing now, and be completed prior to Render()
Page.RegisterAsyncTask(new PageAsyncTask(Asyncer));
base.OnLoad(e);
}
private async Task Asyncer()
{
List<Task<Item[]>> foos = new List<Task<Item[]>>();
CacheManager.ClearAllCaches(); // start with empty Sitecore caches
// For test data we'll grab every item in the database, split up asynchronously by children of /sitecore
var rootItems = Sitecore.Context.Database.GetItem("/sitecore").Children;
var sw = new Stopwatch();
sw.Start();
// ASYNC - go get the children of the root in parallel
// note: it's actually kinda important to have the lambda in there that calls Acquire()
foreach(Item root in rootItems) {
foos.Add(Task.Run(() => Acquire(root)));
}
// wait till all the async queries return
var asyncResults = await Task.WhenAll(foos);
_taskResults.AddRange(asyncResults);
sw.Stop();
Page.Response.Write("Async in " + sw.ElapsedMilliseconds + "ms <br>");
CacheManager.ClearAllCaches();
sw.Restart();
// SYNCHRONOUS - get all children iteratively
foreach (Item root in rootItems)
{
_taskResults.Add(Acquire(root));
}
sw.Stop();
Page.Response.Write("Sync in " + sw.ElapsedMilliseconds + "ms <br>");
}
private Item[] Acquire(Item context)
{
return context.Axes.GetDescendants();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment