Add context.IsCanceled to provide a non-throwing alternative to ThrowIfCanceled. (#1106)

This commit is contained in:
Ahson Khan 2020-12-10 15:01:12 -08:00 committed by GitHub
parent 0f854ffa9b
commit c22392e943
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 1 deletions

View File

@ -391,12 +391,18 @@ namespace Azure { namespace Core {
= ContextSharedState::ToMsecSinceEpoch(time_point::min());
}
/**
* @brief Check if the context is canceled.
* @return `true` if this context is canceled, `false` otherwise.
*/
bool IsCanceled() const { return CancelWhen() < std::chrono::system_clock::now(); }
/**
* @brief Throw an exception if the context was canceled.
*/
void ThrowIfCanceled() const
{
if (CancelWhen() < std::chrono::system_clock::now())
if (IsCanceled())
{
throw OperationCanceledException("Request was canceled by context.");
}

View File

@ -8,6 +8,7 @@
#include <chrono>
#include <memory>
#include <string>
#include <thread>
#include <vector>
using namespace Azure::Core;
@ -80,6 +81,18 @@ TEST(Context, BasicChar)
EXPECT_TRUE(kind == ContextValue::ContextValueType::StdString);
}
TEST(Context, IsCanceled)
{
auto duration = std::chrono::milliseconds(150);
auto deadline = std::chrono::system_clock::now() + duration;
Context context;
auto c2 = context.WithDeadline(deadline);
EXPECT_FALSE(c2.IsCanceled());
std::this_thread::sleep_for(duration);
EXPECT_TRUE(c2.IsCanceled());
}
TEST(Context, Alternative)
{
Context context;