简体   繁体   English

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

[英]How to make asynchronous call with timeout

I want to make an asynchronous call in C++ with timeout, meaning I want to achieve sth like that. 我想在C ++中使用超时进行异步调用,这意味着我想要实现这样的功能。

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

EDIT : Where function is a method that takes a lot of time and I want to interrupt it when it takes too much time. 编辑:函数是一种需要大量时间的方法,我想在花费太多时间时中断它。 I' ve been looking for how to achieve it and I thinki boost::asio::deadline_timer is way to go. 我一直在寻找实现它的方法,我认为boost::asio::deadline_timer是可行的方法。 I guess calling timer.async_wait(boost::bind(&A::fun, this, args)) is what I need, but I do not know how to find if the call was success or was aborted due to timeout. 我想打电话给timer.async_wait(boost::bind(&A::fun, this, args))是我所需要的,但是我不知道如何找到呼叫是成功还是由于超时而中止。

EDIT: after the answer from ForEveR my code now looks like this. 编辑:从ForEveR的答案后,我的代码现在看起来像这样。

    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;
}
}

I wanted to pass the timer by reference and cancel it in the end of asynchronous method, but I got an error that I cannot access private member declared in class ::boost::asio::basic_io_object. 我想通过引用传递计时器,并在异步方法的最后将其取消,但是出现一个错误,我无法访问在:: boost :: asio :: basic_io_object类中声明的私有成员。

Maybe using the deadline timer is not that good idea ? 也许使用截止时间计时器不是一个好主意吗? I would really appreciate any help. 我真的很感谢您的帮助。 I am passing the timer to the function, because the method that calls the asynchronous method is asynchronous itself and thus I cannot have one timer for whole class or sth like that. 我将计时器传递给该函数,因为调用异步方法的方法本身就是异步的,因此我不能为整个类或某物设置一个计时器。

You should use boost::asio::placeholders::error 您应该使用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
   {
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM