[我们希望演员在一段时间不活动后停止播放(即,它在x分钟内未收到某种消息后停止播放)。我没有对此的任何内置支持,因此我选择使用调度程序。
actor本身将自身预定的消息设置为其自身,如下所示:
Context
.System
.Scheduler
.ScheduleTellRepeatedly(_expiryInterval, _expiryInterval, Self, new ExpiryCheckMessage(), Self);
收到此消息后:
Receive<ExpiryCheckMessage>(x => {
if(IsExpired())
{
Context.Stop(Self);
}
});
但是在终止和终止actor之后,计划的消息将继续发送,从而导致死信。
在这种情况下,停止预定消息的最佳方法是什么?
NB:我熟悉JVM上的Akka,而不是.Net上的。
From the Akka docs for ScheduleTellRepeatedly似乎存在类型为cancelable
的可选ICancelable
参数。因此,我想像这样的东西(这实际上是我尝试编写的第一个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);
}
}