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_
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/callback.h"
13 #include "base/logging.h"
14 #include "base/post_task_and_reply_with_result_internal.h"
15 #include "base/task_runner.h"
19 // When you have these methods
21 // R DoWorkAndReturn();
22 // void Callback(const R& result);
24 // and want to call them in a PostTaskAndReply kind of fashion where the
25 // result of DoWorkAndReturn is passed to the Callback, you can use
26 // PostTaskAndReplyWithResult as in this example:
28 // PostTaskAndReplyWithResult(
29 // target_thread_.task_runner(),
31 // BindOnce(&DoWorkAndReturn),
32 // BindOnce(&Callback));
33 template <typename TaskReturnType, typename ReplyArgType>
34 bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
35 const Location& from_here,
36 OnceCallback<TaskReturnType()> task,
37 OnceCallback<void(ReplyArgType)> reply) {
40 TaskReturnType* result = new TaskReturnType();
41 return task_runner->PostTaskAndReply(
43 BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, std::move(task),
45 BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
46 std::move(reply), Owned(result)));
49 // Callback version of PostTaskAndReplyWithResult above.
50 // Though RepeatingCallback is convertible to OnceCallback, we need this since
51 // we cannot use template deduction and object conversion at once on the
52 // overload resolution.
53 // TODO(crbug.com/714018): Update all callers of the Callback version to use
55 template <typename TaskReturnType, typename ReplyArgType>
56 bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
57 const Location& from_here,
58 Callback<TaskReturnType()> task,
59 Callback<void(ReplyArgType)> reply) {
60 return PostTaskAndReplyWithResult(
61 task_runner, from_here, OnceCallback<TaskReturnType()>(std::move(task)),
62 OnceCallback<void(ReplyArgType)>(std::move(reply)));
67 #endif // BASE_TASK_RUNNER_UTIL_H_