1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_CRITICAL_CLOSURE_H_
6 #define BASE_CRITICAL_CLOSURE_H_
10 #include "base/callback.h"
11 #include "base/location.h"
12 #include "base/strings/string_piece.h"
13 #include "build/build_config.h"
16 #include "base/bind.h"
17 #include "base/ios/scoped_critical_action.h"
25 // Returns true if multi-tasking is supported on this iOS device.
26 bool IsMultiTaskingSupported();
28 // This class wraps a closure so it can continue to run for a period of time
29 // when the application goes to the background by using
30 // |ios::ScopedCriticalAction|.
31 class CriticalClosure {
33 explicit CriticalClosure(StringPiece task_name, OnceClosure closure);
34 CriticalClosure(const CriticalClosure&) = delete;
35 CriticalClosure& operator=(const CriticalClosure&) = delete;
40 ios::ScopedCriticalAction critical_action_;
43 #endif // defined(OS_IOS)
45 } // namespace internal
47 // Returns a closure that will continue to run for a period of time when the
48 // application goes to the background if possible on platforms where
49 // applications don't execute while backgrounded, otherwise the original task is
53 // file_task_runner_->PostTask(
55 // MakeCriticalClosure(task_name,
56 // base::BindOnce(&WriteToDiskTask, path_, data)));
58 // Note new closures might be posted in this closure. If the new closures need
59 // background running time, |MakeCriticalClosure| should be applied on them
60 // before posting. |task_name| is used by the platform to identify any tasks
61 // that do not complete in time for suspension.
63 inline OnceClosure MakeCriticalClosure(StringPiece task_name,
64 OnceClosure closure) {
65 DCHECK(internal::IsMultiTaskingSupported());
66 return base::BindOnce(
67 &internal::CriticalClosure::Run,
68 Owned(new internal::CriticalClosure(task_name, std::move(closure))));
71 inline OnceClosure MakeCriticalClosure(const Location& posted_from,
72 OnceClosure closure) {
73 return MakeCriticalClosure(posted_from.ToString(), std::move(closure));
76 #else // defined(OS_IOS)
77 inline OnceClosure MakeCriticalClosure(StringPiece task_name,
78 OnceClosure closure) {
79 // No-op for platforms where the application does not need to acquire
80 // background time for closures to finish when it goes into the background.
84 inline OnceClosure MakeCriticalClosure(const Location& posted_from,
85 OnceClosure closure) {
89 #endif // defined(OS_IOS)
93 #endif // BASE_CRITICAL_CLOSURE_H_