FAQ - Help and questions

How does C# async and await compare with Rust async, and why does my future do nothing?

#porting#csharp#asyncpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A C# Task is already running when the async method returns it. A Rust future is only a value describing work, and nothing happens until it is awaited or handed to a runtime such as Tokio. Rust also has no built-in runtime, so a program needs one. Task.WhenAll corresponds to tokio join.

Checked with rustc 1.93.0, tokio 1.54.1, .NET SDK 10.0.302, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

The keywords match (async, await) and the result looks similar, but the two models start work at different moments, and ports trip over that.

C#Rust
What calling an async function returnsA Task<T> that has already started runningA Future that has not started; it is a state machine value
When the work beginsAt the call, up to the first await that must waitWhen the future is first polled, usually by .await
Who runs itThe runtime built into .NET (the thread pool and synchronisation context)A runtime library that you choose and add, such as Tokio
Running several at onceTask.WhenAll(a, b)tokio::join!(a, b) (same task), or tokio::spawn (separate tasks)
CancellingA CancellationToken that you pass and checkDropping the future cancels it at the next await

Both programs call an async function that prints "started", waits, then prints "done". They print what happens between the call and the await.

C# (.NET SDK 10.0.302):

csharp
static async Task<int> Work(string name, int ms)
{
    Console.WriteLine($"  {name}: started");
    await Task.Delay(ms);
    Console.WriteLine($"  {name}: done");
    return ms;
}

Console.WriteLine("calling Work(a)");
var t = Work("a", 30);          // a Task is already running when the call returns
Console.WriteLine("after the call");
Console.WriteLine($"result {await t}");
text
calling Work(a)
  a: started
after the call
  a: done
result 30

Rust (rustc 1.93.0, Tokio 1.54.1 with the features rt-multi-thread, macros, time and sync):

src/main.rsrust
use std::time::Duration;
use tokio::time::sleep;

async fn work(name: &str, ms: u64) -> u32 {
    println!("  {name}: started");
    sleep(Duration::from_millis(ms)).await;
    println!("  {name}: done");
    ms as u32
}

#[tokio::main]
async fn main() {
    println!("calling work(a)");
    let fut = work("a", 30); // nothing has run yet: this is only a value describing the work
    println!("after the call");
    let r = fut.await; // it starts here
    println!("result {r}");

    println!("sequential awaits, then join");
    let t = std::time::Instant::now();
    let _ = work("b", 50).await;
    let _ = work("c", 50).await;
    let sequential = t.elapsed();
    let t = std::time::Instant::now();
    let (x, y) = tokio::join!(work("d", 50), work("e", 50));
    let joined = t.elapsed();
    println!("sums {}  sequential took more than 100 ms: {}  joined took less than 100 ms: {}", x + y, sequential.as_millis() >= 100, joined.as_millis() < 100);
}
text
calling work(a)
after the call
  a: started
  a: done
result 30
sequential awaits, then join
  b: started
  b: done
  c: started
  c: done
  d: started
  e: started
  e: done
  d: done
sums 100  sequential took more than 100 ms: true  joined took less than 100 ms: true

The difference is in the second line of each output. In C# a: started appears before after the call, because the Task started when it was created. In Rust it appears after, because nothing ran until .await. The second half of the Rust program shows two awaits in a row taking at least 100 ms, and join! running two 50 ms waits together in under 100 ms. The C# program has the matching Task.WhenAll check, and printed the same two results (the order of the last two "done" lines may differ from run to run in both languages).

How to do it#

  1. Add a runtime to Cargo.toml (for example tokio with the features you use) and mark main with #[tokio::main].
  2. Port async Task<T> methods to async fn ... -> T. Port await x to x.await.
  3. Where C# relied on a task starting at once ("fire and forget"), call tokio::spawn(future); it returns a handle you can await later, and the task runs without being awaited.
  4. Port Task.WhenAll to tokio::join! for a fixed number of futures, or to a set of spawned tasks you await in a loop.
  5. Port CancellationToken to dropping the future, to tokio::select! with a shutdown signal, or to a token type from a crate such as tokio-util (not run here).
  6. Do not block in async code: use tokio::time::sleep instead of std::thread::sleep, and move CPU-heavy work to spawn_blocking.

Common mistakes#

  • Calling an async function and ignoring the result. The compiler warns that futures do nothing unless used; do not silence it.
  • Holding a std::sync::Mutex guard across an .await. The future may then be moved between threads while the lock is held, which the compiler often rejects; use a short critical section or Tokio's own mutex.
  • Mixing runtimes. Libraries written for one runtime may not work under another.

Is a Rust future bigger or smaller than a Task?#

A future is a plain value on the stack or in a box. It holds the state its async fn needs between awaits. This thread did not measure sizes.

Do I need async at all?#

Not for every program. Threads are simpler for a small number of long jobs. Async helps when many tasks wait on I/O.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet