master
h 58 lines 1.33 KB
Raw
1 /*++
2
3 Copyright (c) Microsoft. All rights reserved.
4
5 Module Name:
6
7 retryshared.h
8
9 Abstract:
10
11 This file contains shared retry helper functions.
12
13 --*/
14
15 #pragma once
16
17 namespace wsl::shared::retry {
18
19 constexpr auto AlwaysRetry = []() { return true; };
20
21 template <typename T, typename TPeriod, typename TTimeout>
22 T RetryWithTimeout(const std::function<T()>& routine, TPeriod retryPeriod, TTimeout timeout, const std::function<bool()>& retryPred = AlwaysRetry)
23 {
24 auto stop = std::chrono::steady_clock::now() + timeout;
25 for (;;)
26 {
27 try
28 {
29 return routine();
30 }
31 catch (...)
32 {
33 if (!retryPred() || std::chrono::steady_clock::now() > stop)
34 {
35 throw;
36 }
37
38 std::this_thread::sleep_for(retryPeriod);
39 }
40 }
41 }
42
43 #ifdef WIN32
44
45 template <typename T, typename TPeriod, typename TTimeout>
46 T RetryWithTimeout(const std::function<T()>& routine, TPeriod retryPeriod, TTimeout timeout, std::vector<HRESULT>&& retryErrors)
47 {
48 auto pred = [retryErrors = std::move(retryErrors)]() {
49 auto hr = HRESULT_FROM_WIN32(GetLastError());
50 return std::find(retryErrors.begin(), retryErrors.end(), hr) != retryErrors.end();
51 };
52
53 return RetryWithTimeout(routine, retryPeriod, timeout, pred);
54 }
55
56 #endif
57
58 } // namespace wsl::shared::retry