Thursday, December 20, 2012

Monitor a Task time out

There are some ways to wait for a task timeout. This is the simplest:
using System.Threading.Tasks;

[...]

try
{
    Task executeTask = STask.Factory.StartNew(() => DoSomething());

    //Wait for 5 minutes
    int index = System.Threading.Tasks.Task.WaitAny(new[] { executeTask },
     TimeSpan.FromSeconds(300));

    if (index == -1)
    {
        //Task execution Time Out
    }
    else
    {
        //Task executed in-time
    }
}
catch (AggregateException aex)
{
    foreach (Exception ex in aex.InnerExceptions)
        LogError(ex, ex.Message);
}
catch (Exception ex)
{
    LogError(ex, "Error");
}

No comments: