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_TASK_RUNNER_UTIL_H_
6 #define BASE_TASK_RUNNER_UTIL_H_
9 #include "base/bind_helpers.h"
10 #include "base/callback_internal.h"
11 #include "base/logging.h"
12 #include "base/task_runner.h"
18 // Helper class for TaskRunner::PostTaskAndReplyWithResult.
19 template <typename ReturnType
>
20 void ReturnAsParamAdapter(const Callback
<ReturnType(void)>& func
,
26 // Helper class for TaskRunner::PostTaskAndReplyWithResult.
27 template <typename ReturnType
>
28 Closure
ReturnAsParam(const Callback
<ReturnType(void)>& func
,
31 return Bind(&ReturnAsParamAdapter
<ReturnType
>, func
, result
);
34 // Helper class for TaskRunner::PostTaskAndReplyWithResult.
35 template <typename ReturnType
>
36 void ReplyAdapter(const Callback
<void(ReturnType
)>& callback
,
39 if(!callback
.is_null())
40 callback
.Run(CallbackForward(*result
));
43 // Helper class for TaskRunner::PostTaskAndReplyWithResult.
44 template <typename ReturnType
, typename OwnedType
>
45 Closure
ReplyHelper(const Callback
<void(ReturnType
)>& callback
,
47 return Bind(&ReplyAdapter
<ReturnType
>, callback
, result
);
50 } // namespace internal
52 // When you have these methods
54 // R DoWorkAndReturn();
55 // void Callback(const R& result);
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:
61 // PostTaskAndReplyWithResult(
62 // target_thread_.message_loop_proxy(),
64 // Bind(&DoWorkAndReturn),
66 template <typename ReturnType
>
67 bool 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(
75 internal::ReturnAsParam
<ReturnType
>(task
, result
),
76 internal::ReplyHelper(reply
, Owned(result
)));
81 #endif // BASE_TASK_RUNNER_UTIL_H_