I have a method that contains an infinite loop. I call that method from main method and I want to cancel it if it takes more that 2 seconds. I tried these approaches
Task.WhenAny with cancellation of the non completed tasks and timeout
How can I cancel Task.WhenAll?
How to cancel a task using a CancellationToken and await Task.WhenAny
and lots of other links, but non has worked. here is my code
static void Main(string[] args) { var cts = new CancellationTokenSource(2000); var task = Task.Run(() => RunTask(), cts.Token); await task; } public static void RunTask() { while (true) { Console.WriteLine("in while"); } } I also tried to cancel my token but it didn't work. It is not possible to Dispose the task. I don't have access to RunTask source code. I just can run it. I cannot send CancellationToken to my method. How can I terminate RunTask() method?