using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskTimeOut
{
class Program
{
static void Main(string[] args)
{
TimeSpan timeout = TimeSpan.FromMilliseconds(5000);
Task timeOutTask = Task.Factory.StartNew(() =>
{
try
{
// Simulate the long running computation
Thread.Sleep(10000);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}, TaskCreationOptions.LongRunning);
// With TaskCreationOptions.LongRunning option, it will have a dedicated Thread for it's execution and does not interfere with normal behavior of ThreadPool by occupying a thread from there for too long.
if (!timeOutTask.Wait(timeout))
{
// throw exception or something else if timeout
Console.WriteLine("Time Out");
Console.ReadKey();
}
}
}
}
Date start = new Date();
// Some stuff ....,
// Get HTML Page
Date end = new Date();