2011-02-25 89 views
5

异步连接中有定时器的一个方面,我想知道我是否理解正确。一些需要说明的内容Boost asio异步操作和定时器

假设我们在执行读操作之前设置了一个定时器,其中包含一个处理程序,然后是 io_service。

正如我已经明白该io_service一旦经理被调用后的结束而结束,它可以发生,原因有二:

一)读操作完成。 b)定时器已达到极限。

假设已经达到第一个(a)条件,并且在定时器结束之前读操作已经完成。

问题是:该计时器会发生什么?我们需要完成它吗?说

dTimer_.expires_from_now (boost::posix_time::seconds(0)); 

after the io_service.run()? 

你能重置为一个新的区间,如果有必要重复使用相同的定时器对象另一个读操作?

我可以重置()io_service并重新使用该新操作的新run()中的同一对象吗?如果你不cancel

void my_read_handler() { 
    dTimer_.cancel(); // remember to catch exceptions 
} 

async_wait handler将传递的boost::asio::error::operation_abortederror code如果它成功取消

回答

8

The question is: What happens to that timer? Do we need to finish it.

计时器的处理程序将仍然被调用。如果async_waitcancel之前完成,并且处理程序已经被io_service排队,那么您的处理程序将需要检测该条件并做出适当的反应。


Can you reset it to a new interval if necessary re-use the same timer object for another read operation?

甲deadline_timer可使用expires_from_now

This function sets the expiry time. Any pending asynchronous wait operations will be cancelled. The handler for each cancelled operation will be invoked with the boost::asio::error::operation_aborted error code.


Can I reset() the io_service and reuse the same object in a new run() for that new operation?

相同io_service对象可以resetting之后被再次使用,以run()poll()它是reset

This function must be called prior to any second or later set of invocations of the run(), run_one(), poll() or poll_one() functions when a previous invocation of these functions returned due to the io_service being stopped or running out of work. This function allows the io_service to reset any internal state, such as a "stopped" flag.

+0

全面的回答,+ 1的boost :: ASIO ::错误:: operation_aborted – Ralf 2011-02-25 17:58:49

+0

非常感谢您参与的过程中你的明确和清晰的解释,但仍然是一个问题:假设我的第一个方案,如果有是一个读操作和一个定时器,当第一个结束时io_service结束了吗?前者?或两者? – 2011-02-25 18:36:45

+0

@Old newbie io_service :: run()在没有更多工作要做时将控制权返回给调用者,这在[documentation](http://www.boost.org/doc/libs/1_46_0)中有详细描述/doc/html/boost_asio/reference/io_service/run/overload1.html)。在你的上下文中,它意味着所有优秀的处理程序,'async_read'和'async_wait',将在它返回之前被调用。 – 2011-02-25 20:28:03