Tasks, Continuations and Cancellation

Port async-shaped code to Sharp Runtime with explicit native scheduling and lifetime.

AdvancedTutorial

Translate the control flow

A Task is a compatibility abstraction, not C# language syntax. Express creation, continuation, waiting and cancellation through the implemented C++ API and make the scheduling boundary visible in code review.

Observe cooperative cancellation

#include <iostream>

#include "System/Threading/CancellationToken.hpp"
#include "System/Threading/CancellationTokenSource.hpp"
#include "System/Threading/Tasks/Task.hpp"
#include "System/Threading/Tasks/TaskCanceledException.hpp"

using System::Threading::CancellationToken;
using System::Threading::CancellationTokenSource;
using System::Threading::Tasks::TaskCanceledException;
using System::Threading::Tasks::TaskT;

int main()
{
    CancellationTokenSource source;
    const CancellationToken token = source.getTokenProperty();
    source.Cancel();

    auto task = TaskT<int>::Run([token] {
        token.ThrowIfCancellationRequested();
        return 42;
    }, token);

    try {
        (void)task.Wait();
    } catch (const TaskCanceledException&) {
        std::cout << "canceled\n";
        return 0;
    }
    return 1;
}
Built and run

Against the pinned source, the task reports canceled and exits successfully. Passing a token does not interrupt arbitrary work: running code must poll it or call ThrowIfCancellationRequested().

Lifetime checklist

  • Who owns the work state until completion?
  • Can a continuation run after its UI/game/component owner is destroyed?
  • Which cancellation source controls shutdown?
  • Does teardown wait/join, or deliberately detach?
  • How are exceptions observed and propagated?

Execution differences

Tasks start eagerly through native std::async; Wait() returns or rethrows directly rather than wrapping faults in a managed AggregateException. Single-thread Emscripten cannot provide this surface without pthreads.

Channels

Use Threading.Channels for producer/consumer flow when it matches the port. Decide bounded capacity, full behavior, completion and cancellation instead of inheriting implicit assumptions from the C# scheduler.

No magic await

Sharp Runtime cannot add the C# async/await grammar or CLR synchronization-context semantics to C++.