summaryrefslogtreecommitdiffstats
path: root/base/critical_closure.h
blob: ac07911089d3226a60a45367222f7165c143ec97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_CRITICAL_CLOSURE_H_
#define BASE_CRITICAL_CLOSURE_H_

#include "base/callback.h"

#if defined(OS_IOS)
#include "base/bind.h"
#include "base/ios/scoped_critical_action.h"
#endif

namespace base {

namespace internal {

#if defined(OS_IOS)
// Returns true if multi-tasking is supported on this iOS device.
bool IsMultiTaskingSupported();

// This class wraps a closure so it can continue to run for a period of time
// when the application goes to the background by using
// |ios::ScopedCriticalAction|.
template <typename R>
class CriticalClosure {
 public:
  explicit CriticalClosure(const Callback<R(void)>& closure)
      : closure_(closure) {}

  ~CriticalClosure() {}

  R Run() {
    return closure_.Run();
  }

 private:
  ios::ScopedCriticalAction critical_action_;
  Callback<R(void)> closure_;

  DISALLOW_COPY_AND_ASSIGN(CriticalClosure);
};
#endif  // defined(OS_IOS)

}  // namespace internal

// Returns a closure (which may return a result, but must not require any extra
// arguments) that will continue to run for a period of time when the
// application goes to the background if possible on platforms where
// applications don't execute while backgrounded, otherwise the original task is
// returned.
//
// Example:
//   file_message_loop_proxy_->PostTask(
//       FROM_HERE,
//       MakeCriticalClosure(base::Bind(&WriteToDiskTask, path_, data)));
//
// Note new closures might be posted in this closure. If the new closures need
// background running time, |MakeCriticalClosure| should be applied on them
// before posting.
#if defined(OS_IOS)
template <typename R>
Callback<R(void)> MakeCriticalClosure(const Callback<R(void)>& closure) {
  DCHECK(internal::IsMultiTaskingSupported());
  return base::Bind(&internal::CriticalClosure<R>::Run,
                    Owned(new internal::CriticalClosure<R>(closure)));
}
#else  // defined(OS_IOS)
template <typename R>
inline Callback<R(void)> MakeCriticalClosure(const Callback<R(void)>& closure) {
  // No-op for platforms where the application does not need to acquire
  // background time for closures to finish when it goes into the background.
  return closure;
}
#endif  // defined(OS_IOS)

}  // namespace base

#endif  // BASE_CRITICAL_CLOSURE_H_