Abort by ajax a loop on the server c #

0

how are they? I have a problem that I do not know how to solve it ... I hope you can help me. I tell you, by ajax I make a call to the server that stays in loop until a card is passed through a reader connected by com port. If the user makes the call and passes the card there is no problem, the problem occurs when the call is made by mistake and you want to cancel the loop remaining in the server. I tried the abort () but I do not function, it remains in queue until it gives timeout on the server (by the loop) ... I hope I have been as clear as possible, thank you.

    
asked by Gonzalo Cayafa 10.07.2018 в 22:15
source

1 answer

-1

Try adding a CancellationToken to your answer and generating a new method that receives it as a parameter and from there you abort your task.

Something like this:

 public class HomeController : Controller
    {
        private static readonly ConcurrentDictionary<Guid, CancellationTokenSource> 
            Tokens = new ConcurrentDictionary<Guid, CancellationTokenSource>();


        public ActionResult LoopLargo()
        {
            var source = new CancellationTokenSource();
            var token = source.Token;

            var guid = Guid.NewGuid();
            token.ThrowIfCancellationRequested();
            Tokens.TryAdd(guid, source);

            var task = Task.Run(async () => {
                //Logica...
                await Task.Delay(10000);
            }, token);

        //Puedes agregar esto también en el cuerpo de la respuesta
        Response.Headers.Add("X-CancellationTokenId", guid.ToString());

            return View();
        }

        public ActionResult DetenerTarea(Guid tokenId)
        {
            if (Tokens.TryGetValue(tokenId, out CancellationTokenSource source))
                source.Cancel();

            return Json("Tarea cancelada");

        }
    }

More information about cancellation of tasks:

link

    
answered by 10.07.2018 в 23:01