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 returns | A Task<T> that has already started running | A Future that has not started; it is a state machine value |
| When the work begins | At the call, up to the first await that must wait | When the future is first polled, usually by .await |
| Who runs it | The runtime built into .NET (the thread pool and synchronisation context) | A runtime library that you choose and add, such as Tokio |
| Running several at once | Task.WhenAll(a, b) | tokio::join!(a, b) (same task), or tokio::spawn (separate tasks) |
| Cancelling | A CancellationToken that you pass and check | Dropping 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):
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}");calling Work(a)
a: started
after the call
a: done
result 30Rust (rustc 1.93.0, Tokio 1.54.1 with the features rt-multi-thread, macros, time and sync):
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);
}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: trueThe 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#
- Add a runtime to
Cargo.toml(for exampletokiowith the features you use) and markmainwith#[tokio::main]. - Port
async Task<T>methods toasync fn ... -> T. Portawait xtox.await. - 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. - Port
Task.WhenAlltotokio::join!for a fixed number of futures, or to a set of spawned tasks you await in a loop. - Port
CancellationTokento dropping the future, totokio::select!with a shutdown signal, or to a token type from a crate such astokio-util(not run here). - Do not block in async code: use
tokio::time::sleepinstead ofstd::thread::sleep, and move CPU-heavy work tospawn_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::Mutexguard 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.
Related questions#
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#
- The Rust Book, "Fundamentals of Asynchronous Programming": https://doc.rust-lang.org/book/ch17-00-async-await.html
- Tokio tutorial: https://tokio.rs/tokio/tutorial