How to Do Asynchronous I/O with Akka.NET Actors Using PipeTo
13 minutes to readOne of the first questions developers ask once they learn how Akka.NET actors work is
If actors can only process one message at a time, can I still use
async
methods orTask<T>
objects inside my actors?
The answer is yes! You can still use asynchronous methods and Task<T>
objects inside your actors - using the PipeTo
pattern!
(2/05/2022) Update
We have completely revised our guidance around await
vs. PipeTo
in our latest post”: Async / Await vs. PipeTo in Akka.NET Actors”
(8/20/2016) Update
Since Akka.NET 1.0 was released, Akka.NET actors have fully supported async
/ await
inside actors. But there’s a catch involved. We still strongly recommend PipeTo
over asyc
/ await
for performance and cohesion reasons but there are scenarios where the latter makes life easier. Keep reading!
Actors Process Messages One at A Time
So actors process the contents of their inbox like this:
The actor’s mailbox pushes a new message into the actor’s OnReceive
method once the previous call to OnReceive
exits.
This is an important concept, because this is how Akka.NET enforces thread-safety for all of the code that executes inside an actor - by making sure an actor’s message processing code (
OnReceive
) can only be run one invocation at a time.
That being said, it’s still possible to take advantage of async
methods and methods that return Task<T>
objects inside the OnReceive
method - you just have to use the PipeTo
extension method!