非actor类向actor发送同步消息,如下所示:
val response = WorkData !? "hello"
如果我想立即回复此消息,我会这样做:
receive {
case "hello" => reply("world")
}
但如果我将来需要回复一段时间,那么 我如何存储来电者参考,然后发送回复?
答案 0 :(得分:4)
对当前来电者的引用存储在sender
。例如,替换
receive {
case "hello" => reply("world")
}
带
receive {
case "hello" => sender ! "world"
}
您可以将此ref存储在可变变量中,或者通过actor的循环递归传递。
答案 1 :(得分:4)
我通常存储发件人引用以便以后使用它。
receive {
case "hello" =>
val otherParty = sender
// more receives, etc
// ...
otherParty ! "world"
}
答案 2 :(得分:1)
如何生成一个处理消息并在准备就绪时响应的匿名actor?这样接收器就可以充当调度员。这不需要一个可变变量来存储任何东西,因为你在这里使用了一个闭包。
import scala.actors.Actor
import scala.actors.Actor._
case class Message(msg: String)
class MyReceiver extends Actor {
def act() {
react {
case Message(msg) =>
actor {
sender ! process(msg)
}
}
}
def process(msg: String): String =
"Result: " + msg
}
object Main {
def main(args: Array[String]) {
val a = new MyReceiver
a.start()
val res = a !? Message("foo")
println(res)
}
}
问候,raichoo