2011-02-25 92 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