I have a code which depends on a cancellation token with zero timeout to bail out early. This is the snippet
using System;
using System.Threading;
namespace ConsoleApp2
{
class Program
{
void DoIdleWait(TimeSpan timeout, CancellationToken cancellationToken)
{
var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
linkedCancellationTokenSource.CancelAfter(timeout);
while (!linkedCancellationTokenSource.IsCancellationRequested)
{
Console.WriteLine("Waiting");
}
}
static void Main(string[] args)
{
var prog = new Program();
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(2));
prog.DoIdleWait(TimeSpan.Zero, cts.Token);
}
}
}
Since the timeout is zero, I expect it not to enter the if block, but it's not doing that. Any idea why this is happening? Also, any way to achieve what I am trying to do?