如何减少ReceiveActor的代码重复

时间:2016-11-11 08:06:52

标签: c# .net akka akka.net

我接收了具有可切换行为的Actor,由Become()方法切换。要监视子actor,我必须添加Receive<终止>呼吁每个州的方法。

例如,我必须将其粘贴到Ready,Working1和Working2方法

public class SomeActor : ReceiveActor
{
    public SomeActor()
    {
        // create child actors
        Become(Ready);
    }

    private void Ready()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working1);
        });

        Receive<Terminated>(m =>
        {
            // duplicated termination stuff 
            Become(Terminated);
        });
    }

    private void Working1()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working2);
        });

        Receive<Terminated>(m =>
        {
            // duplicated termination stuff 
            Become(Terminated);
        });
    }

    private void Working2()
    {
        Receive<InitParcerMessage>(m =>
        {
            Become(Working1);
        });

        Receive<Terminated>(m =>
        {
            // duplicated termination stuff 
            Become(Terminated);
        });
    }

    private void Terminated()
    {
        // do some stuff
    }
}

1 个答案:

答案 0 :(得分:0)

您正在使用lambda来执行操作,而是可以创建一个私有方法,该方法将Terminated类型作为参数,并在MethodGroup操作中使用Receive

public class SomeActor : ReceiveActor
{
    public SomeActor()
    {
        // create child actors
        Become(Ready);
    }

    private void Ready()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working1);
        });

        ConfigureReceive();
    }

    private void Working1()
    {
        Receive<InitMessage>(m =>
        {
            Become(Working2);
        });

        ConfigureReceive();
    }

    private void Working2()
    {
        Receive<InitParcerMessage>(m =>
        {
            Become(Working1);
        });

        ConfigureReceive();
    }

    private void Terminated()
    {
        // do some stuff
    }

    private void ConfigureReceive()
    {
        // Register Receive actors here
        Receive<Terminated>(p => HandleTermination(p));
    }

    // Here's our method to perform the same job with our Terminated parameter
    private void HandleTermination(Terminated termination)
    {
        // Call our Become method
        Become(Terminated);
    }
}