continuable icon indicating copy to clipboard operation
continuable copied to clipboard

How to cancel a task based on timeout?

Open qiangxinglin opened this issue 1 year ago • 1 comments

@Naios Thank you for the bravo project!

I want to implement a sync interface, suppose we have a response struct:

  • Post a task to the executor
  • If it can be finished in the timeout, then retrieve the result, and return response{success, result}.
  • If it takes longer than the timeout, return response(fail, "timeout"), and set the running continuable to fail status.

I have following code

auto task = asio::post(ioc, use_continuable).then([=]() { // where ioc is a asio::io_context running in a worker thread
    this_thread::sleep_for(300ms); // simulate some long task
    return 42;
})
auto res = std::move(task).apply(transforms::wait_for(50ms));
if (res.is_value())
    return response{success, *res};
else
    return response{fail, "timeout"}; // how to invalidate the task above?

qiangxinglin avatar Nov 01 '23 08:11 qiangxinglin

Hi @qiangxinglin , you can use when_any and combine it with a timer. Continuable does not support real cancellation of continuations and you would have to implement this for your specific task.

Naios avatar Dec 14 '23 21:12 Naios