Twisted Python – 如果延迟超出范围,是否会被解雇?

如果我创建一个Deferred并在reactor事件循环中添加一些回调,如果我让本地引用超出范围,它是否会被调用?例如,如果我有一个带有connectionMade()的协议,如下所示:

def connectionMade(self):
    # This made up function returns a deferred that will connect to 
    # some remote server using some made up protocol and return some data.
    d = connectToRemoteServer(reactor, url)
    d.addCallback(self._handleRemoteConnection)
    # At this point, d is going to go out of scope, so will the deferred
    # it points to ever get fired?

def _handleRemoteConnection(self, data):
    # Do something with the data

我在使用Twisted的不同代码中看到了这种模式,我无法理解为什么从connectToRemoteServer()返回的延迟不是
当d超出范围时收集的垃圾.我认为它永远不会发生,或者由于竞争条件而无法随机失败.任何人都可以向我解释为什么这有效吗?我已经读了几次http://twistedmatrix.com/documents/current/core/howto/defer.html,但我仍然不确定为什么这会起作用?

谢谢,

卡尔

最佳答案 假设的connectToRemoteServer API将在内部保存对d的引用,通常使用从全局reactor到对象的引用,当d表示的操作完成时,该对象将触发d(通过调用d.callback).

因此,引用从堆栈到reactor.run的堆栈帧(因为反应器正在运行)到d.

点赞