From c22392e9437773e228941dbd1353b5ff56166e04 Mon Sep 17 00:00:00 2001 From: Ahson Khan Date: Thu, 10 Dec 2020 15:01:12 -0800 Subject: [PATCH] Add context.IsCanceled to provide a non-throwing alternative to ThrowIfCanceled. (#1106) --- sdk/core/azure-core/inc/azure/core/context.hpp | 8 +++++++- sdk/core/azure-core/test/ut/context.cpp | 13 +++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/sdk/core/azure-core/inc/azure/core/context.hpp b/sdk/core/azure-core/inc/azure/core/context.hpp index 164dec8e7..e304abab9 100644 --- a/sdk/core/azure-core/inc/azure/core/context.hpp +++ b/sdk/core/azure-core/inc/azure/core/context.hpp @@ -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."); } diff --git a/sdk/core/azure-core/test/ut/context.cpp b/sdk/core/azure-core/test/ut/context.cpp index c6d30fc7b..90b061a70 100644 --- a/sdk/core/azure-core/test/ut/context.cpp +++ b/sdk/core/azure-core/test/ut/context.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include 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;