Created
October 29, 2013 02:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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