gpt4 book ai didi

c++ - boost::asio::deadline_timer renew 仍然调用处理函数

转载 作者:行者123 更新时间:2023-11-30 03:02:22 25 4
gpt4 key购买 nike

在下面的官方boost链接中: http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/reference/deadline_timer.html .

您可以看到我们可以在异步 deadline_timer 到期之前更新它。很好,代码有效:当计时器更新时,旧的 async_wait 被取消了,这很好,但烦人的是当它被取消时,它仍然调用处理程序:

void handler(const boost::system::error_code& error)
{
if (!error)
{
// Timer expired.
}
}

...

// Construct a timer with an absolute expiry time.
boost::asio::deadline_timer timer(io_service,
boost::posix_time::time_from_string("2005-12-07 23:59:59.000"));

// Start an asynchronous wait.
timer.async_wait(handler);

更改事件的 deadline_timer 的到期时间

在有挂起的异步等待时更改计时器的到期时间会导致这些等待操作被取消。为确保与计时器关联的操作只执行一次,请使用如下内容: used:

void on_some_event()
{
if (my_timer.expires_from_now(seconds(5)) > 0)
{
// We managed to cancel the timer. Start new asynchronous wait.
my_timer.async_wait(on_timeout);
}
else
{
// Too late, timer has already expired!
}
}

void on_timeout(const boost::system::error_code& e)
{
if (e != boost::asio::error::operation_aborted)
{
// Timer was not cancelled, take necessary action.
}
}

我想知道有没有办法在不让旧计时器调用处理程序的情况下更新和取消旧计时器,在这种情况下是 on_timeout() 函数

最佳答案

可以通过在执行实际操作之前添加一行检查(查看它是否是中止/取消事件)来修复它:

void handler1(const boost::system::error_code &e)
{
if (e != boost::asio::error::operation_aborted) // here is the important part
{
//do actual stuff here if it's not a cancel/abort event
}
}

关于c++ - boost::asio::deadline_timer renew 仍然调用处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10212408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com