locked
Cancelling a Long Running Task Delay in Web API RRS feed

  • Question

  • User-813878398 posted

    I am trying to cancel a async delay task (Task.Delay) that was created by a web api request, with an another web api request that issues cancel. It does not look like it cancelled the timer for task.delay. Here is the code snippet that I am trying to implement. For your information I am using Application object to store the CancellationTokenSource object to retrieve the token source across multiple requests. Question is I am expecting the task to be cancelled by throwing an exception from the code. But it never happened. How do I make this code to cancel the task.delay?

    using Microsoft.Practices.Unity;
    using System;
    using System.Collections.Concurrent;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    
    namespace WebApplication8.Controllers
    {
        public class TaskController : ApiController
        {
            [HttpGet]
            public async Task<string> CreateTask(int id)
            {
                var tokenSource = new CancellationTokenSource();
    
                var concurrentTokens = GetConcurrentTokens();
    
                concurrentTokens.TryAdd(id, tokenSource);
    
                CancellationToken token = tokenSource.Token;
                token.ThrowIfCancellationRequested();
    
                await Task.Delay(50000,token);
    
                return "Task Created";
            }
    
    
            [HttpGet]
            public async Task<string> Cancel(int id)
            {
                var concurrentTokens = GetConcurrentTokens();
                CancellationTokenSource item = concurrentTokens.First(t => t.Key == id).Value;
                item.Cancel();
                item.Dispose();
                var tokenSource2 = new CancellationTokenSource();
                concurrentTokens.TryRemove(id,out tokenSource2);
                return "Cancelled";
            }
    
            private ConcurrentDictionary<long, CancellationTokenSource> GetConcurrentTokens()
            {
                var tokens = HttpContext.Current.Application["Tokens"];
    
                 if (tokens == null)
                 {
                    tokens = new ConcurrentDictionary<long, CancellationTokenSource>();
                    HttpContext.Current.Application["Tokens"] = tokens;
                 }
    
                 return (ConcurrentDictionary<long, CancellationTokenSource>) tokens;
            }
        }
    }

     

    Saturday, January 28, 2017 3:52 AM

All replies

  • User1169094377 posted

    You need to call Cancel method rather than remove

    please check this

    https://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource(v=vs.110).aspx

    Sunday, January 29, 2017 12:09 PM