异步 60 秒延迟后在 C++ 中执行函数?

Execute function in C++ after asynchronous 60 sec delay?

我读过这可以通过使用 std::this_thread::sleep_forstd::async[ 来实现=25=],但它对我不起作用。

这里是要调用的函数:

bool Log::refresh_data()
{   

    std::this_thread::sleep_for( std::chrono::minutes( 1 ) );

    std::vector<std::string> file_info = this->file.read_pending_if();

    for( auto line : file_info )
    {
        this->append( line );
    }

    return true;
}

这是从另一个函数调用的。下面的代码中有两个使用失败的例子:

void MVC::refresh_data()
{
    // Error C3867  'Log::refresh_data': non-standard syntax; use '&' to create a pointer to member
    std::future<bool> retCode = std::async( this->model_log.refresh_data, 0 );        
    std::future<bool> retCode = std::async( this->model_log.refresh_data(), 0 );
}

最初,bool Log::refresh_data()void Log::refresh_data() std::async 似乎不喜欢 void return...

因为 refresh_dataLog 的一个方法,你需要使用 std::bindmodel_log,或者使用 lambda:

std::future<bool> retCode = std::async( [this] {return model_log.refresh_data(); }); 

你不能在 C++ 中传递这样的非静态方法,你可以这样做:

auto retCode = std::async(&Log::refresh_data, model_log);
// Or with a lambda:
auto retCode = std::async([this]() { 
    return model_log.refresh_data(); 
});

这些代码适用于 void return 类型(您只需删除 lambda 中的 return 语句)。