5

I have an IPClient actor which manages/owns a connection which is expensive to open/close.

Before the actor finishes handling a message, I'd like to peek at the top of the actor's Mailbox to check if there is another message pending. - If the actor has got more work, leave the connection open. - If the actor has emptied it's mailbox, close the connection.

Here's the gist of what i'm thinking:

public void Handle(PollDevice message)
    {
        if (!_client.IsConnected)
            _client.Connect();

        var results = _client.GetData()

        var actorHasMoreWork = Context.Dispatcher.Mailboxes.???
        if (!actorHasMoreWork)
            _client.Disconnect();

        Sender.Tell(true);
    }

Is this possible? Is it the best way?

daveharnett
  • 340
  • 2
  • 12
  • Does _client have state specific to this actor? Wondering if you could just use pooled connections where you have a pool of actors that keep open connections and this actor in the example forwards messages to them – tomliversidge Sep 25 '16 at 08:30
  • Just happened upon this question and was wondering if you were able to peek at the mailbox? (Hmm, I think I saw that there used to be a PeekMailbox that was something else - let you pull the next message from the mailbox without removing it - but it got deprecated.) I was just going to say that my working-with-what-I-know solution to this would have been to leave the connection open by default but have the actor send a simple... – mwardm Jul 28 '17 at 23:40
  • ...message to itself at the end of your method (while also keeping an instance-level reference to the message). If that just-sent message was the next message received, there was clearly nothing in the queue, so go ahead and close the connection. – mwardm Jul 28 '17 at 23:41

1 Answers1

3

I have a partial answer.

You can get an actor's mailbox's ID (but not the mailbox itself) with Context.Props.Mailbox

And once you have an actor's mailbox (which, again, the previous step will not give you), my understanding of the documentation says you should be able to use either Mailbox.MessageQueue.HasMessages or Mailbox.MessageQueue.Count to get information about the contents. As far as I can tell, you would not be able to see any of the messages without dequeuing them.

I have not been able to determine a way to get the Mailbox object, however, and I've actually found some evidence it is not currently possible in Akka.Net. There is a GitHub issue about making this possible that's been open since September 2014, and the last update is also from September 2014.

octothorpentine
  • 319
  • 2
  • 18
  • 1
    Actually the GitHub issue was updated in November 2018 with code to retrieve the mailbox size: https://github.com/akkadotnet/akka.net/issues/383#issuecomment-436523926 – Luca Cremonesi Oct 31 '19 at 19:07