ASP.NET Weblogs

Welcome to ASP.NET Weblogs Sign in | Join | Help
in Search

The Technical Adventures of Adam Weigert

PLINQ Adventure Land - WaitForAll

PLINQ is awesome for getting a lot of work done fast, but one thing I haven't figured out yet is how to start work with PLINQ but only let it execute for a maximum amount of time and react if it is taking too long. So, as I must admit I am still learning PLINQ, I created this extension in that ignorance. It behaves similar to ForAll<> but takes a timeout and returns false if the threads don't complete in the specified amount of time. Hope this helps someone else take PLINQ further, it definitely has helped for me ...

 

public static bool WaitForAll<T>(this ParallelQuery<T> query, TimeSpan timeout, Action<T> action)
{
    Contract.Requires(query != null);
    Contract.Requires(action != null);

    var exception = (Exception)null;
    var cts = new CancellationTokenSource();
            
    var forAllWithCancellation = new Action(delegate
    {
        try
        {
            query.WithCancellation(cts.Token).ForAll(action);
        }
        catch (OperationCanceledException)
        {
            // NOOP
        }
        catch (AggregateException ex)
        {
            exception = ex;
        }
    });
            
    var mrs = new ManualResetEvent(false);
    var callback = new AsyncCallback(delegate { mrs.Set(); });
    var result = forAllWithCancellation.BeginInvoke(callback, null);
            
    if (mrs.WaitOne(timeout))
    {
        forAllWithCancellation.EndInvoke(result);

        if (exception != null)
        {
            throw exception;
        }

        return true;
    }
    else
    {
        cts.Cancel();
        return false;
    }
}

Comments

 

SamZ said:

Could you add sample of using this?

Please

May 24, 2010 2:11 AM
 

Twitter Trackbacks for PLINQ Adventure Land - WaitForAll - The Technical Adventures of Adam Weigert [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 PLINQ Adventure Land - WaitForAll - The Technical Adventures of Adam Weigert         [asp.net]        on Topsy.com

May 24, 2010 2:40 AM
 

adweigert said:

I've added an example of how I use this here weblogs.asp.net/.../the-waitforall-roadshow.aspx

May 26, 2010 8:57 AM
 

adweigert said:

Woot, found the Parallel Task library that is part of .NET 4.0; use that instead!

msdn.microsoft.com/.../dd537609(v=VS.100).aspx

May 29, 2010 9:10 AM