When you are dealing with large amounts of data or processes that are very time hungry you sometimes need the ability to timeout that task and continue.
Here is a snippet of code that loops around that takes 1 second, and you can set a timeout to any time you like, but if it is less than 1 second, it will cancel the task and free up resources.
class Program
{
public static void Main()
{
int timeOutInMilliseconds = 450;
var startTime = DateTime.Now;
var cTokenSource = new CancellationTokenSource();
// Create a cancellation token from CancellationTokenSource
var cToken = cTokenSource.Token;
// Create a task and pass the cancellation token
var t1 = Task<int>.Factory.StartNew(() => GenerateNumbers(cToken), cToken);
// to register a delegate for a callback when a cancellation request is made
cToken.Register(() => cancelNotification(cTokenSource));
while (true)
{
if(t1.IsCompleted)
{
Console.WriteLine("Finished Processing");
break;
}
if (DateTime.Now > startTime.AddMilliseconds(timeOutInMilliseconds))
{
Console.WriteLine("Timed out");
cTokenSource.Cancel();
break;
}
}
Console.WriteLine("finished");
Console.ReadLine();
}
private static Task HandleTimer(CancellationTokenSource cancellationTokenSource)
{
cancellationTokenSource.Cancel();
Console.WriteLine("\nHandler not implemented...");
return Task.Run(() => { var a = 0; });
}
static int GenerateNumbers(CancellationToken cancellationTokenSource)
{
int i;
for (i = 0; i < 10; i++)
{
Console.WriteLine("Method1 - Number: {0}", i);
Thread.Sleep(100);
// poll the IsCancellationRequested property
// to check if cancellation was requested
if (cancellationTokenSource.IsCancellationRequested)
break;
}
return i;
}
// Notify when task is cancelled
static void cancelNotification(CancellationTokenSource cancellationTokenSource)
{
cancellationTokenSource.Cancel();
}
}
Source: Parallel