blob: d1b9f62fcd6b25abf788324e118979421c738e03 [file] [log] [blame]
[email protected]95991b12012-04-17 02:48:061// 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.
4
5#ifndef BASE_TASK_RUNNER_UTIL_H_
6#define BASE_TASK_RUNNER_UTIL_H_
[email protected]95991b12012-04-17 02:48:067
8#include "base/bind.h"
9#include "base/bind_helpers.h"
[email protected]d53e6a62012-05-03 22:34:1710#include "base/callback_internal.h"
[email protected]95991b12012-04-17 02:48:0611#include "base/logging.h"
12#include "base/task_runner.h"
13
14namespace base {
15
16namespace internal {
17
18// Helper class for TaskRunner::PostTaskAndReplyWithResult.
19template <typename ReturnType>
20void ReturnAsParamAdapter(const Callback<ReturnType(void)>& func,
21 ReturnType* result) {
22 if (!func.is_null())
23 *result = func.Run();
24}
25
26// Helper class for TaskRunner::PostTaskAndReplyWithResult.
27template <typename ReturnType>
28Closure ReturnAsParam(const Callback<ReturnType(void)>& func,
29 ReturnType* result) {
30 DCHECK(result);
31 return Bind(&ReturnAsParamAdapter<ReturnType>, func, result);
32}
33
34// Helper class for TaskRunner::PostTaskAndReplyWithResult.
35template <typename ReturnType>
36void ReplyAdapter(const Callback<void(ReturnType)>& callback,
37 ReturnType* result) {
38 DCHECK(result);
39 if(!callback.is_null())
[email protected]d53e6a62012-05-03 22:34:1740 callback.Run(CallbackForward(*result));
[email protected]95991b12012-04-17 02:48:0641}
42
43// Helper class for TaskRunner::PostTaskAndReplyWithResult.
44template <typename ReturnType, typename OwnedType>
45Closure ReplyHelper(const Callback<void(ReturnType)>& callback,
46 OwnedType result) {
47 return Bind(&ReplyAdapter<ReturnType>, callback, result);
48}
49
50} // namespace internal
51
52// When you have these methods
53//
54// R DoWorkAndReturn();
55// void Callback(const R& result);
56//
57// and want to call them in a PostTaskAndReply kind of fashion where the
58// result of DoWorkAndReturn is passed to the Callback, you can use
59// PostTaskAndReplyWithResult as in this example:
60//
61// PostTaskAndReplyWithResult(
62// target_thread_.message_loop_proxy(),
63// FROM_HERE,
64// Bind(&DoWorkAndReturn),
65// Bind(&Callback));
66template <typename ReturnType>
67bool PostTaskAndReplyWithResult(
68 TaskRunner* task_runner,
69 const tracked_objects::Location& from_here,
70 const Callback<ReturnType(void)>& task,
71 const Callback<void(ReturnType)>& reply) {
72 ReturnType* result = new ReturnType;
73 return task_runner->PostTaskAndReply(
74 from_here,
75 internal::ReturnAsParam<ReturnType>(task, result),
76 internal::ReplyHelper(reply, Owned(result)));
77}
78
79} // namespace base
80
81#endif // BASE_TASK_RUNNER_UTIL_H_