template class mrpt::imgui::AsyncTask

Overview

Runs a computation on a background thread, and lets the GUI thread poll for its result once per frame without blocking, so long operations (e.g.

loading a large file) never stall the event loop.

Starting a new computation while one is running supersedes it: the old one is asked to cancel, and its result is discarded when it finishes.

mrpt::imgui::AsyncTask<Scene::Ptr> loader;
loader.start([file](AsyncTaskContext& ctx) { return loadScene(file, ctx); });
// Every frame:
if (auto scene = loader.poll(); scene) { ... }
if (loader.isRunning()) { ImGui::ProgressBar(loader.progress()); }
#include <mrpt/imgui/AsyncTask.h>

template <typename T>
class AsyncTask
{
public:
    // typedefs

    typedef std::function<T(AsyncTaskContext&)> worker_t;

    // construction

    AsyncTask();
    AsyncTask(const AsyncTask&);

    // methods

    AsyncTask& operator = (const AsyncTask&);
    void start(worker_t fn);
    void start(std::function<T()> fn);
    bool isRunning() const;
    uint64_t generation() const;
    double progress() const;
    std::string progressMessage() const;
    void cancel();
    void cancelAndWait();
    std::optional<T> poll();
};

Methods

void start(worker_t fn)

Starts fn on a background thread (cancelling any running one).

void start(std::function<T()> fn)

Starts a worker that needs no progress or cancellation support.

uint64_t generation() const

Number of computations started so far (so callers can tell results of different runs apart).

double progress() const

Progress reported by the running worker, in [0,1].

void cancel()

Asks the running worker to stop (it must poll cancelRequested()), and forgets about it: its result, if any, is never returned by poll().

The worker thread is not waited for.

void cancelAndWait()

Like cancel(), but waits for the worker to finish, e.g.

before destroying data it uses.

std::optional<T> poll()

Call once per frame: returns the result exactly once, on the first call after the worker finished, and nullopt otherwise.

If the worker threw, the exception is rethrown here.