在CLI / C ++中限制API调用的运行时间

问题描述 投票:0回答:1

我想限制我在C ++ / CLI引用类中等待API调用响应的时间。

我已经看过C#中的following code,看起来像我想要的:

var task = Task.Run(() =>
{
    return LongRunningMethod();
});

bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(3000));

if (isCompletedSuccessfully)
{
    return task.Result;
}
else
{
    throw new TimeoutException("The function has taken longer than the maximum time allowed.");
}

如何获取此代码“翻译”到CLI / C ++?看起来Task.Run不能立即运行。

为了记录,我的“ LongRunningMethod”类似于:

            bool my_client::CanContactServer()
            {
                bool isAvailable = static_cast<bool>(m_p_client->contactServer());

                return isAvailable;
            }
c++ multithreading c++-cli
1个回答
1
投票

C ++ / CLI不支持lambda,但是您仍然可以将委托传递给Task.Run方法。您的代码将如下所示:

// I suppose you have an instance of my_client initialized somewhere
my_client^ client = gcnew my_client(); 

Func<bool>^ f = gcnew Func<bool>(client, &my_client::CanContactServer);
Task<bool>^ task = Task::Run(f);

bool isCompletedSuccessfully = task->Wait(TimeSpan::FromMilliseconds(3000));

if (isCompletedSuccessfully)
{
    return task->Result;
}
else
{
    throw gcnew TimeoutException("The function has taken longer than the maximum time allowed.");
}
© www.soinside.com 2019 - 2024. All rights reserved.