task_runner_util.h 1.65 KB
Newer Older
1 2 3 4 5 6 7
// 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_TASK_RUNNER_UTIL_H_
#define BASE_TASK_RUNNER_UTIL_H_

8 9
#include <utility>

10 11
#include "base/bind.h"
#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 16 17 18 19 20 21 22 23 24 25 26 27 28
#include "base/task_runner.h"

namespace base {

// When you have these methods
//
//   R DoWorkAndReturn();
//   void Callback(const R& result);
//
// and want to call them in a PostTaskAndReply kind of fashion where the
// result of DoWorkAndReturn is passed to the Callback, you can use
// PostTaskAndReplyWithResult as in this example:
//
// PostTaskAndReplyWithResult(
skyostil's avatar
skyostil committed
29
//     target_thread_.task_runner(),
30 31 32
//     FROM_HERE,
//     Bind(&DoWorkAndReturn),
//     Bind(&Callback));
33
template <typename TaskReturnType, typename ReplyArgType>
34 35 36 37
bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
                                const tracked_objects::Location& from_here,
                                Callback<TaskReturnType()> task,
                                Callback<void(ReplyArgType)> reply) {
38 39
  DCHECK(task);
  DCHECK(reply);
40
  TaskReturnType* result = new TaskReturnType();
41
  return task_runner->PostTaskAndReply(
42 43 44 45 46
      from_here,
      base::BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>,
                     std::move(task), result),
      base::BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
                     std::move(reply), base::Owned(result)));
47 48 49 50 51
}

}  // namespace base

#endif  // BASE_TASK_RUNNER_UTIL_H_