7

我可能做错了什么,但并不明显。我有以下代码:

 namespace test
    {
        class Program
            {
             static void Main(string[] args)

                {
                    using (var system = ActorSystem.Create("MySystem"))
                    {
                        var testPassRetriever = system.ActorOf<PrintActor>();
                        var task = testPassRetriever.Ask<PrintActorMsg>(new PrintActorMsg());

                        // prevent the application from exiting before message is handled
                        task.Wait();
                        Console.WriteLine("Finished.");
                        Console.ReadLine();
                    }
                }
        }
        class PrintActorMsg{}

        class PrintActor : ReceiveActor
        {
            public PrintActor()
            {
             Receive<PrintActorMsg>(msg => Console.WriteLine("foo"));
            }
        }
}// namespace test

问题是 Ask 返回的任务永远不会完成。其状态保持在等待激活状态。“Foo”确实打印在命令行上,所以我知道演员正在处理打印消息。在被覆盖的演员 PrintMsg 中我还应该做些什么来标记任务已完成?

4

2 回答 2

10

您使用询问模式,但从不发回消息。只有在收到来自参与者的消息时,才会完成询问任务。(有时建议)告诉或即发即弃模式不会这样做。

于 2015-06-01T21:23:18.410 回答
0

只是为了将来读者的完整性,因为 OP 的原始问题似乎不希望从被调用的 Actor 返回任何响应/结果有效负载,所以 OP 应该使用该Tell模式,而不是Ask,例如用于火灾和忘记调度场景:

 class PrintActor : ReceiveActor
 {
    public PrintActor()
    {
        // Response to the message, with no response
        Receive<PrintActorMsg>(msg => Console.WriteLine("foo"));
    }
 }

并在调用程序中

var myActor = system.ActorOf<PrintActor>();
// One way 'fire and forget'
await myActor.Tell(new PrintActorMsg());

而如果需要 Ask 请求-响应类型交互,则接收参与者需要通过显式Tell返回给发送者提供响应(PrintResponse是一个新的响应消息类):

 public class ResponseActor : ReceiveActor
 {
    public ResponseActor()
    {
       Receive<PrintActorMsg>(msg => {
         Console.WriteLine("foo"));

         // ... Other handling code here

         // Must return a response for an Ask
         Sender.Tell(new PrintResponse(), Self);
       });
    }
 }

像这样称呼

var response = await actor.Ask<PrintResponse>(new PrintActorMsg(), TimeSpan.FromSeconds(5));

请注意,添加异常处理也是一个好主意。

于 2021-11-30T16:00:38.443 回答