Skip to content

Instantly share code, notes, and snippets.

@enricosoft
Created May 2, 2023 17:09
Show Gist options
  • Save enricosoft/ffd7ddacb29db95c7a635527b4f4945d to your computer and use it in GitHub Desktop.
Save enricosoft/ffd7ddacb29db95c7a635527b4f4945d to your computer and use it in GitHub Desktop.
Akka.NET Sample
namespace AkkaRoomReservationSample
{
class Program
{
static void Main(string[] args)
{
var system = ActorSystem.Create("MySystem");
IActorRef reservator = system.Actorof<ReservationActor>("reservator");
reservator.Tell (new BookThe Room { RoomNumber = "1"} );
reservator.Tell(new BookTheRoom { RoomNumber = "1" });
Console.Read();
}
}
public class ReservationActor : ReceiveActor
{
private readonly List<RoomState> _rooms = new List<RoomState>(){
new RoomState {RoomNumber = "1", IsBooked = false},
new RoomState {RoomNumber = "2", IsBooked = true},
new RoomState {RoomNumber = "3", IsBooked = true}
};
public ReservationActor()
{
Receive<BookTheRoom>(msg =>
{
var availableRoom = _rooms.SingleOrDefault(x=> x.RoomNumber == msg.RoomNumber && !x.IsBooked);
if(availableRoom != null){
availableRoom.IsBooked = true;
Self.Tell(new RoomBooked(){ RoomNumber = msg.RoomNumber });
}
else{
Self.Tell(new RoomBusy() { RoomNumber = msg.RoomNumber });
}
});
Receive<RoomBooked>(msg = > Console.WriteLine($"Room {msg.RoomNumber} booked"));
Receive<RoomBusy>(msg = > Console.WriteLine($"Room {msg.RoomNumber} busy"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment