task_runner_util.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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.
  4. #ifndef BASE_TASK_RUNNER_UTIL_H_
  5. #define BASE_TASK_RUNNER_UTIL_H_
  6. #include <memory>
  7. #include <utility>
  8. #include "base/bind.h"
  9. #include "base/callback.h"
  10. #include "base/check.h"
  11. #include "base/post_task_and_reply_with_result_internal.h"
  12. #include "base/task_runner.h"
  13. namespace base {
  14. // When you have these methods
  15. //
  16. // R DoWorkAndReturn();
  17. // void Callback(const R& result);
  18. //
  19. // and want to call them in a PostTaskAndReply kind of fashion where the
  20. // result of DoWorkAndReturn is passed to the Callback, you can use
  21. // PostTaskAndReplyWithResult as in this example:
  22. //
  23. // PostTaskAndReplyWithResult(
  24. // target_thread_.task_runner(),
  25. // FROM_HERE,
  26. // BindOnce(&DoWorkAndReturn),
  27. // BindOnce(&Callback));
  28. //
  29. // DEPRECATED: Prefer calling|task_runner->PostTaskAndReplyWithResult(...)|
  30. // directly.
  31. // TODO(gab): Mass-migrate to the member method.
  32. template <typename TaskReturnType, typename ReplyArgType>
  33. bool PostTaskAndReplyWithResult(TaskRunner* task_runner,
  34. const Location& from_here,
  35. OnceCallback<TaskReturnType()> task,
  36. OnceCallback<void(ReplyArgType)> reply) {
  37. DCHECK(task);
  38. DCHECK(reply);
  39. // std::unique_ptr used to avoid the need of a default constructor.
  40. auto* result = new std::unique_ptr<TaskReturnType>();
  41. return task_runner->PostTaskAndReply(
  42. from_here,
  43. BindOnce(&internal::ReturnAsParamAdapter<TaskReturnType>, std::move(task),
  44. result),
  45. BindOnce(&internal::ReplyAdapter<TaskReturnType, ReplyArgType>,
  46. std::move(reply), Owned(result)));
  47. }
  48. } // namespace base
  49. #endif // BASE_TASK_RUNNER_UTIL_H_