gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:17:43 25 4
gpt4 key购买 nike

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

我看过 following code在 C# 中看起来像我想要的:

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++/CLI 不支持 lambda,但您仍然可以将委托(delegate)传递给 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.");
}

关于c++ - 在 CLI/C++ 中限制 API 调用的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58094705/

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