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");
if(task.Wait(timeout))line as documented here: msdn.microsoft.com/en-us/library/dd235606.aspx – Rob White Sep 21 '12 at 14:43