Is there any way to wait for the actor to stop completely?

As I know, all operations in Akka.Net are asynchronous, but Context.Stop()simply sends a message to the Stopactor. This means that the actor will be alive for some time before he is completely disconnected.

And if I call Context.Child()right after Context.Stop()with the name of the actor, I just stopped, I will get the same actor.

Here is a sample code

var actor = context.Child(actorName);

if (actor.Equals(ActorRefs.Nobody))
{
    actor = CreateNewActor();
}

Context.Stop(actor)
actor = context.Child(actorName);
// what do we get here, same actor or ActorRefs.Nobody ?

My application creates participants for handling events from terminals. Each time a new terminal is connected, I create a new actor by calling Context.Child()using the name of the terminal. When the terminal shuts down, I stop the actor.

, Connect Disconnect , , . , "" ?

+4
2

Terminated.

Disconnect ActorsToBeStopped HashSet, Connect, , . , Connect Connect .

- :

private readonly Dictionary<string, Connect> postponedConnectMessages = new Dictionary<string, Connect>();
private readonly HashSet<string> actorsToBeStopped = new HashSet<string>();

// ...

Receive<Disconnected>(t => 
{
    var actor = GetActorByName(t.Name);
    Context.Stop(actor);
    actorsToBeStopped.Add(actor.Path.Name);
});

Receive<Connected>(t =>
{
    var actor = GetActorByName(t.Name);

    if (actorsToBeStopped.Contains(actor.Path.Name))
    {
        postponedConnectMessages[actor.Path.Name] = t;
        return;
    }
    // work with actor
}

Receive<Terminated>(t =>
{
    var deadActorName = t.ActorRef.Path.Name;
    actorsToBeStopped.Remove(deadActorName);
    if (postponedConnectMessages.ContainsKey(deadActorName))
    {
        var connectMessage = postponedConnectMessages[deadActorName];
        postponedConnectMessages.Remove(deadActorName);
        var actor = GetActorByName(connectMessage.Name);
        // we sure we have new actor here
        // work with actor
    }
}

, , Akka.TestKit TestActor :

public void StopTest()
{ 
    var t = CreateTestActor("AAAA");
    Watch(t);
    Sys.Stop(t);
    ExpectTerminated(t, TimeSpan.FromSeconds(10));
    var t2 = CreateTestActor("AAAA"); // test fails here
}

, , ExpectTerminated, , .

0

var shutdown = actor.GracefulStop(TimeSpan.FromSeconds(42));

, 42

UPDATE

, , Terminated message .

0

Source: https://habr.com/ru/post/1665984/


All Articles