azure Reliable actors


Example

An actor inside Service Fabric is defined by a standard .NET interface/class pair:

public interface IMyActor : IActor
{
    Task<string> HelloWorld();
}


internal class MyActor : Actor, IMyActor
{
    public Task<string> HelloWorld()
    {
        return Task.FromResult("Hello world!");
    }
}

Every method in the interface/class pair must be async, and they cannot have out or ref paramenters.

It is easy to understand why if you think about the actor model: objects interacting with each other through exchange of messages. The messages are delivered to an actor class through the async methods; responses are handled by the actors runtime (the actor "container") and routed back to the caller.

The Service Fabric SDK will generate a proxy at compile time. This proxy is used by the actor client to call its methods (i.e. to deliver a message to the actor and await a response).

The client identifies an Actor through a ID. The ID can be already known (you got it from a DB, from another Actor, or maybe it is the userID linked to that actor, or again the serial number of a real object).

If you need to create a new actor and you just need an ID, the (provided) ActorId class has methods to create a randomly distributed actor ID

ActorId actorId = ActorId.NewId();

Then, you can use the ActorProxy class to creates a proxy object for the actor. This does not activate an actor or invoke any methods yet. IMyActor myActor = ActorProxy.Create(actorId, new Uri("fabric:/MyApp/MyActorService"));

Then, you can use the proxy to invoke a method on the actor. If an actor with the given ID does not exist, it will be activated (created inside one of the containers in the cluster), and then the runtime will post a message to the actor, executing its method call and completing the Task when the actor answers:

await myActor.HelloWorld();