停止重复的预定消息

Stopping a repeating scheduled message

我们希望 actor 在一段时间不活动后(即在 x 分钟内未收到某种消息后)自行停止。我没有看到对此有任何内置支持,所以我选择使用调度程序。

actor自己给自己设置一个定时消息,如下:

Context
    .System
    .Scheduler
    .ScheduleTellRepeatedly(_expiryInterval, _expiryInterval, Self, new ExpiryCheckMessage(), Self);

收到此消息时:

Receive<ExpiryCheckMessage>(x => {
    if(IsExpired())
    {
        Context.Stop(Self);
    }
});

但是在 actor 过期并停止后,计划的消息继续发送导致死信。

在这种情况下停止预定消息的最佳方法是什么?

注意:我熟悉 JVM 上的 Akka,而不是 .Net 上的。

From the Akka docs for ScheduleTellRepeatedly 似乎有一个类型为 ICancelable 的可选 cancelable 参数。所以我想像这样的东西(这实际上是我尝试编写的第一个 C#,所以提前道歉):

// Somewhere in the actor's scope
var cancellationKey = new Cancelable(Context.System.Scheduler);

Context
    .System
    .Scheduler
    .ScheduleTellRepeatedly(
        _expiryInterval,
        _expiryInterval, 
        Self,
        new ExpiryCheckMessage(),
        Self, 
        cancellationKey
    );

Receive<ExpiryCheckMessage>(x =>
    if (IsExpired()) {
        cancellationKey.Cancel();
        Context.Stop(Self);
    }
}