---
title: "Run Atomics.waitAsync in C#"
url: https://recursiveai.org/oneecma/cookbook/resolve-javascript-atomic-waits-with-virtual-time/
description: "Run JavaScript Atomics.waitAsync from C#. See FIFO notification and virtual timeouts without parallel workers or wall-clock blocking."
version: "1.1.1"
---

# Run Atomics.waitAsync in C#

**OneEcma** is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneEcma) · [GitHub](https://github.com/recursive-ai-oss/oneecma-csharp) · [Docs](https://recursiveai.org/oneecma/docs/) · [Download example (.zip)](https://recursiveai.org/oneecma/cookbook/resolve-javascript-atomic-waits-with-virtual-time/resolve-javascript-atomic-waits-with-virtual-time.zip)

Virtual time lets a wait expire without a wall-clock delay or a second JavaScript worker.

```shell
dotnet add package RecursiveAI.OneEcma
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneEcma;

var engine = new ScriptEngine();
var promise = engine.Evaluate("""
  const slots = new Int32Array(
    new SharedArrayBuffer(4));
  const wait = () =>
    Atomics.waitAsync(slots, 0, 0, 5).value;
  const waits = [wait(), wait()];
  Atomics.notify(slots, 0, 1);
  Promise.all(waits).then(x => x.join());
  """);
Console.WriteLine(
    engine.Await(promise).AsString);
```

Unzip [the example](https://recursiveai.org/oneecma/cookbook/resolve-javascript-atomic-waits-with-virtual-time/resolve-javascript-atomic-waits-with-virtual-time.zip), then `dotnet run`.

One notification reaches the first waiter; the second times out on the virtual clock.

```text
ok,timed-out
```

## Full program

Two waiters register in order on slot 0 and a third registers on slot 1. Both slots start at zero. Two `notify` calls wake one waiter each on slot 0; the program checks both the return counts and the order of the resolved results.

```csharp
using RecursiveAI.OneEcma;

var engine = new ScriptEngine();
var promise = engine.Evaluate("""
    (async () => {
      const slots = new Int32Array(new SharedArrayBuffer(8));
      const log = [];
      const wait = (name, index) => Atomics.waitAsync(slots, index, 0, 5)
        .value.then(status => log.push(`${name}: ${status}`));
      const first = wait("first", 0);
      const second = wait("second", 0);
      const timeout = wait("other slot", 1);
      log.push(`notified: ${Atomics.notify(slots, 0, 1)}`);
      log.push(`notified: ${Atomics.notify(slots, 0, 1)}`);
      await Promise.all([first, second, timeout]);
      return log.join("\n");
    })()
    """);
var log = engine.Await(promise).AsString;
if (log != "notified: 1\nnotified: 1\nfirst: ok\nsecond: ok\nother slot: timed-out")
    throw new InvalidOperationException($"Unexpected wait results:\n{log}");
Console.WriteLine(log);
```

`dotnet run` prints:

```text
notified: 1
notified: 1
first: ok
second: ok
other slot: timed-out
```

A wait without a finite timeout stays pending if nothing calls `Atomics.notify` for that slot.

## Variations

**Handle a value that has already changed.** If the current value differs from the expected value, `waitAsync` returns `async: false` and a status string instead of a promise.

```csharp
using RecursiveAI.OneEcma;

var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
  const a = new Int32Array(new SharedArrayBuffer(4));
  a[0] = 1;
  const wait = Atomics.waitAsync(a, 0, 0, 5);
  `${wait.async}: ${wait.value}`;
  """).AsString);
```

```text
false: not-equal
```

## Related recipes

- [Await JavaScript promises from C#](https://recursiveai.org/oneecma/cookbook/await-javascript-promises-from-dotnet/)
- [Record and replay JavaScript in C#](https://recursiveai.org/oneecma/cookbook/record-replay/)

## The short answer

Call `Atomics.waitAsync` on an `Int32Array` backed by a `SharedArrayBuffer`. If the slot holds the expected value and the wait is asynchronous, use the returned object’s `value` promise. Call `Atomics.notify` from JavaScript to resolve a pending wait with `"ok"`. With no notification and a finite deadline, OneEcma resolves it with `"timed-out"` using virtual time. In C#, `engine.Await` gets the result of the JavaScript promise.

## What does Atomics.waitAsync return?

[`Atomics.waitAsync`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/waitAsync) returns an object with `async` and `value` properties. The variation shows `async: false` and `value: "not-equal"` because the slot already contains `1`, not the expected `0`. When that happens, there’s no queued wait for `notify` to wake. A matching value with a zero timeout can likewise return `"timed-out"` immediately. Only call `.then` on `value` after checking `async`, unless the input is controlled as it is in the examples.

The timeout is specified in milliseconds, but in OneEcma a finite timeout is a deadline on the engine’s virtual clock. Per the [binary data docs](https://recursiveai.org/oneecma/docs/binary-data/#host-defined-behaviour), when the job queue drains, the earliest pending deadline resolves, with ties in creation order. The engine processes the resulting jobs and continues. No timer thread or real-time delay is needed. Use this to exercise the timeout path of your script, not to measure how long another thread takes to respond.

## How does Atomics.notify choose which waiter to wake?

[`Atomics.notify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/notify) takes the typed array, element index, and optional count, and returns the number of waiters notified. In OneEcma, waiters on a slot resolve first in, first out through a queued job. In the full program the first notification selects `first` and the second selects `second`. The log records notifications first because the promise callbacks run after the synchronous calls. The wait on slot 1 can’t be notified by a call for slot 0, so it resolves by timeout instead.

Schedule the notification before awaiting a result you expect it to wake. If you await that result first and the notification appears only afterward in the same async function, the notification can’t settle it. OneEcma isn’t running a second JavaScript worker to make that happen. Give the wait a finite timeout if your program needs a result when there is no eligible notification.
