I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout(
(Func)delegate { return SomeMethod(someInput); }, 30);
///
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
///
/// Return type of function
/// Function delegate for task to perform
/// Time to allow before task times out
///
private T RunTaskWithTimeout(Func TaskAction, int TimeoutSeconds)
{
Task backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}