如何使用超时进行异步调用

How to make asynchronous call with timeout

本文关键字:异步 调用 何使用 超时      更新时间:2023-10-16

我想在c++中使用timeout进行异步调用,这意味着我想实现类似的目标。

AsynchronousCall(function, time);
if(success)
    //call finished succesfully
else
    //function was not finished because of timeout

编辑:其中函数是一个方法,需要很多时间,我想打断它,当它需要太多的时间。我一直在寻找如何实现它,我认为boost::asio::deadline_timer是一条路。我猜呼叫timer.async_wait(boost::bind(&A::fun, this, args))是我需要的,但我不知道如何查找呼叫是否成功或因超时而中止。

编辑:在永远的答案之后,我的代码现在看起来像这样。

    boost::asio::io_service service;
boost::asio::deadline_timer timer(service);
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait(boost::bind(&A::CheckTimer, this, boost::asio::placeholders::error));
boost::thread bt(&A::AsynchronousMethod, this, timer, args);  //asynchronous launch
void A::CheckTimer(const boost::system::error_code& error)
{
if (error != boost::asio::error::operation_aborted)
{
    cout<<"ok"<<endl;
}
// timer is cancelled.
else
{
    cout<<"error"<<endl;
}
}

我想通过引用传递定时器并在异步方法结束时取消它,但是我得到了一个错误,我无法访问在class::boost::asio::basic_io_object中声明的私有成员。

也许使用截止日期计时器不是个好主意?我将非常感谢任何帮助。我将计时器传递给函数,因为调用异步方法的方法本身是异步的,因此我不能为整个类或类似的东西设置一个计时器。

应该使用boost::asio::placeholders::error

timer.async_wait(boost::bind(
&A::fun, this, boost::asio::placeholders::error));
A::fun(const boost::system::error_code& error)
{
   // timeout, or some other shit happens
   if (error != boost::asio::error::operation_aborted)
   {
   }
   // timer is cancelled.
   else
   {
   }
}