Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have created the following extension method that can be used to fun a function with a timeout applied to it. Is this a sensible way of doing it?

public static class FuncExtensions
{
    public static T RunUntil<T>(this Func<T> predicate, TimeSpan timeout, string taskName)
    {
        var result = default(T);
        Action runTask = () => result = predicate();

        try
        {
            var task = Task.Factory.StartNew(runTask);
            if (task.Wait(timeout))
            {
                return result;
            }

            throw new TaskTimeoutException(string.Format("'{0}' timed out after {1}", taskName, timeout));
        }
        catch (AggregateException aggregateException)
        {
            throw aggregateException.InnerException;
        }
    }
}

Which can be used like this:

Func<int> task = () => { //some slow service };

var serviceResponse = task.RunUntil(_serviceTimeout, "Name of Task");
share|improve this question
1  
I don't see the code which should stop the task if it goes over on time. – Jesse C. Slicer Sep 21 '12 at 13:15
The if(task.Wait(timeout)) line as documented here: msdn.microsoft.com/en-us/library/dd235606.aspx – Rob White Sep 21 '12 at 14:43
2  
Yes, but it doesn't cancel the executing task if you go over the wait time. It'll still be running. – Jesse C. Slicer Sep 21 '12 at 14:44
How to do the cancelling is described here Task Cancellation and additionaly How to: Cancel a Task and Its Children – JorisG Oct 15 '12 at 10:10
This article describes the kind of problem I was dealing with: blogs.msdn.com/b/pfxteam/archive/2012/10/05/… – Rob White Oct 15 '12 at 12:59
show 1 more comment

1 Answer

up vote 0 down vote accepted

The best solution I've found is on this blog:

http://blogs.msdn.com/b/pfxteam/archive/2012/10/05/how-do-i-cancel-non-cancelable-async-operations.aspx

share|improve this answer
3  
You should summarize or quote the relevant contents from the provided link. The link may go dead and this answer becomes useless. – Zuul Oct 15 '12 at 15:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.