ExtensionMethod.NET Home of 877 C#, Visual Basic, F# and Javascript extension methods


Starts execution of IQueryable on a ThreadPool thread and returns immediately with a "end" method to call once the result is needed.


public static Func<TResult> Async<T, TResult>(this IEnumerable<T> enumerable, Func<IEnumerable<T>, TResult> asyncSelector)
    System.Diagnostics.Debug.Assert(!(enumerable is ICollection), "Async does not work on arrays/lists/collections, only on true enumerables/queryables.");

    // Create delegate to exec async
    Func<IEnumerable<T>, TResult> work = (e => asyncSelector(e));

    // Launch it
    IAsyncResult r = work.BeginInvoke(enumerable, null, null);

    // Return method that will block until completed and rethrow exceptions if any
    return () => work.EndInvoke(r);


// Define some expensive query
IQueryable<string> myExpensiveQuery = context.SystemLog.Where(l => l.Timestamp >= DateTime.Today.AddDays(-10));

// Start async processing
Func<string[]> waitForQueryData = myExpensiveQuery.Async(e => e.ToArray());

// Do a lot of other work, e.g. other queries

// Need my query result now, so block until it's ready and get result
string[] myQueryResults = waitForQueryData();

Author: ulrikb.worldpress.com

Submitted on: 14 okt. 2010

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 7450