Fixing exception safety in our task_sequencer -- Raymond Chen
Some time ago, we developed a
task_
class for running asynchronous operations in sequence. There’s a problem with the implementation of QueueTaskAsync
: What happens if an exception occurs?
Fixing Exception Safety in our
task_sequencer
by Raymond Chen
From the article:
Let’s look at the various places an exception can occur in
QueueTaskAsync
.template<typename Maker> auto QueueTaskAsync(Maker&& maker) ->decltype(maker()) { auto current = std::make_shared<chained_task>(); auto previous = [&] { winrt::slim_lock_guard guard(m_mutex); return std::exchange(m_latest, current); ← oops }(); suspender suspend; using Async = decltype(maker()); auto task = [](auto&& current, auto&& makerParam, auto&& contextParam, auto& suspend) -> Async { completer completer{ std::move(current) }; auto maker = std::move(makerParam); auto context = std::move(contextParam); co_await suspend; co_await context; co_return co_await maker(); }(current, std::forward<Maker>(maker), winrt::apartment_context(), suspend); previous->continue_with(suspend.handle); return task; }
If an exception occurs at
make_
, then no harm is done because we haven’t done anything yet.shared If an exception occurs when starting the lambda task, then we are in trouble. We have already linked the
current
ontom_latest
, but we will never callcontinue_
, so the chain of tasks stops making progress.with() To fix this, we need to delay hooking up the
current
to the chain ofchained_
s until we are sure that we have a task to chain.task