1

I've an asynchronous method where I'm running a void-return type method in a Task and I want that method to be cancelled in X time (let's say 5 seconds) if it hasn't completed by then.

I found two similar threads: Cancel long running Task after 5 seconds when not finished Asynchronously wait for Task<T> to complete with timeout but I don't manage to get the cancellation to work using these.

This is what I've so far:

 using (var cts = new CancellationTokenSource(5000))
            {
                await Task.Run(() =>
                {
                    CandySystem.QueryCandies(rowOrderByIndex, columnOrderByIndex,
                        orderByDescending);
                }, cts.Token);
            }

I expect method "QueryCandies" to cancel after running for 5 seconds. Could someone provide me "for dummies" explanation what's going wrong here?

xc3llion
  • 11
  • 2
  • 3
    To somewhat oversimplify, the cancellation token is checked before the task is started, and if it is cancelled then the task won't even be started - otherwise, the code run by the task will need to check a cancellation token itself in order to cancel. (Normally you'd pass the same cancellation token to your task code and check it at some point or points.) The `Task` class itself will NOT attempt to cancel a task once its been started! – Matthew Watson Oct 22 '19 at 14:36
  • @MatthewWatson Ahh silly me. I got it working now, thanks! – xc3llion Oct 23 '19 at 09:49

0 Answers0