Version 7.6.3.2-android, tag libreoffice-7.6.3.2-android
[LibreOffice.git] / include / systools / win32 / retry_if_failed.hxx
blob1372843ab8a6ae495ec57c82483991770844297f
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #pragma once
12 #include <type_traits>
13 #include <systools/win32/uwinapi.h>
15 #pragma comment(lib, "Kernel32.lib") // for Sleep
17 namespace sal::systools
19 // Some system calls (e.g., clipboard access functions) may fail first time, because the resource
20 // may only be accessed by one process at a time. This function allows to retry failed call up to
21 // specified number of times with a specified timeout (in ms), until the call succeeds or the limit
22 // of attempts is exceeded.
23 // Usage:
24 // HRESULT hr = sal::systools::RetryIfFailed(10, 100, []{ return OleFlushClipboard(); });
25 template <typename Func>
26 std::enable_if_t<std::is_same_v<std::invoke_result_t<Func>, HRESULT>, HRESULT>
27 RetryIfFailed(unsigned times, unsigned msTimeout, Func func)
29 for (unsigned i = 0;; ++i)
31 if (HRESULT hr = func(); SUCCEEDED(hr) || i >= times)
32 return hr;
33 Sleep(msTimeout);
38 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */