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