Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Nejra 5 posts 76 karma points
    Jul 07, 2020 @ 14:37

    Parallel.Foreach or similar approach?

    Hi all,

    I have a code that filters X pages to narrow it down based on defined criteria, and then makes new objects out of each page. Page being converted to an object is completely independent, so to speed it up I wanted to run it in a Parallel.ForEach loop, but get exceptions because Umbraco context is null in new threads.

    Is there a way around it?

    Simplified code:

    private static NewClass MakeNewClass(PageObj obj) {
    NewClass cc = new NewClass(){
        Url = obj.Url
    //do stuff to populate cc
    return cc; 
    public static List<NewClass> GetPages(UmbracoHelper umbraco, int pagesRoot) {
    ConcurrentBag<NewClass> ret = new ConcurrentBag<NewClass>();
        var pages = umbraco.TypedContent(pagesRoot).Descendants(PageObj.ModelTypeAlias).Cast<PageObj>();
        //filtering pages etc, but in the end I'm left with a list of pages
        Parallel.ForEach(pages, o => ret.Add(MakeNewClass(o)));         
    catch (Exception exc)
    return ret.ToList(); 
Please Sign in or register to post replies

Write your reply to: