Add context.IsCanceled to provide a non-throwing alternative to ThrowIfCanceled. (#1106)
This commit is contained in:
parent
0f854ffa9b
commit
c22392e943
@ -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.");
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user