Skip to content

Commit

Permalink
AK1003 - Add documentation (#7072)
Browse files Browse the repository at this point in the history
* AK1003 - Add documentation

* Fix layout problem
  • Loading branch information
Arkatufus authored Jan 26, 2024
1 parent 55253f3 commit bdc46f2
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions docs/articles/debugging/rules/AK1003.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
---
uid: AK1003
title: Akka.Analyzers Rule AK1003 - "ReceiveAsync<T>() or ReceiveAnyAsync<T>() message handler without async lambda body"
---

# AK1003 - Warning

You should not have a synchronous code inside lambda function when using [`ReceiveAsync<T>()`](xref:Akka.Actor.ReceiveActor#Akka_Actor_ReceiveActor_ReceiveAsync__1_System_Func___0_System_Threading_Tasks_Task__System_Predicate___0__) or [`ReceiveAnyAsync()`](xref:Akka.Actor.ReceiveActor#Akka_Actor_ReceiveActor_ReceiveAnyAsync_System_Func_System_Object_System_Threading_Tasks_Task__).

## Cause

Using `ReceiveAsync<T>()` or `ReceiveAnyAsync()` with synchronous code inside their lambda function is less performant compared to `Receive<T>()` or `ReceiveAny()` because they generates an extra `ActorTask` message plus an additional suspend + resume of the actor's mailbox. That overhead is fine if you're await-ing something, but if the code is essentially synchronous then you should not do so.

An example:

```csharp
using Akka.Actor;
using System.Threading.Tasks;
using System;

public sealed class MyActor : ReceiveActor
{
public MyActor()
{
// Notice that there are no `await` inside the lambda function,
// The lambda function is essentially synchronous
ReceiveAsync<string>(async str => {
Sender.Tell(str);
}):
}
}
```

## Resolution

Use `Receive<T>()` or `ReceiveAny()` instead.

Here's an example on how to fix the above example:

```csharp
using Akka.Actor;
using System.Threading.Tasks;
using System;

public sealed class MyActor : ReceiveActor
{
public MyActor()
{
// Notice we have replaced `ReceiveAsync` with `Receive`
// and removed the async keyword
Receive<string>(str => {
Sender.Tell(str);
}):
}
}
```

0 comments on commit bdc46f2

Please sign in to comment.