简体   繁体   中英

Cancel an internal task using CancellationToken in ASP.NET Core2.2

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?

Cancellation tokens are a way to request cancellation. It's up to the running code to accept that request and actually stop the work. It's not like killing a process. For example, if you had something like:

public static void RunTask(CancellationToken cancellationToken)
{
   while (!cancellationToken.IsCancellationRequested)
   {
     Console.WriteLine("in while");
   }
}

Then, when it's canceled, the loop will end. However, given that the current code doesn't offer any method of canceling and you cannot modify it, then there is no way to cancel it.

What about this approach:

static void Main(string[] args)
{
   var cts = new CancellationTokenSource(2000);   
   var task = Task.Run(() => RunTask(cts.Token), cts.Token);
   await task;
}

public static void RunTask(CancellationToken token)
{
   while (!token.IsCancellationRequested)
   {
     Console.WriteLine("in while");
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM