async_invoker_inl.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright 2014 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_ASYNC_INVOKER_INL_H_
  11. #define RTC_BASE_ASYNC_INVOKER_INL_H_
  12. #include "api/scoped_refptr.h"
  13. #include "rtc_base/bind.h"
  14. #include "rtc_base/event.h"
  15. #include "rtc_base/message_handler.h"
  16. #include "rtc_base/ref_counted_object.h"
  17. #include "rtc_base/third_party/sigslot/sigslot.h"
  18. #include "rtc_base/thread.h"
  19. #include "rtc_base/thread_annotations.h"
  20. namespace rtc {
  21. class AsyncInvoker;
  22. // Helper class for AsyncInvoker. Runs a task and triggers a callback
  23. // on the calling thread if necessary.
  24. class AsyncClosure {
  25. public:
  26. explicit AsyncClosure(AsyncInvoker* invoker);
  27. virtual ~AsyncClosure();
  28. // Runs the asynchronous task, and triggers a callback to the calling
  29. // thread if needed. Should be called from the target thread.
  30. virtual void Execute() = 0;
  31. protected:
  32. AsyncInvoker* invoker_;
  33. // Reference counted so that if the AsyncInvoker destructor finishes before
  34. // an AsyncClosure's destructor that's about to call
  35. // "invocation_complete_->Set()", it's not dereferenced after being
  36. // destroyed.
  37. scoped_refptr<RefCountedObject<Event>> invocation_complete_;
  38. };
  39. // Simple closure that doesn't trigger a callback for the calling thread.
  40. template <class FunctorT>
  41. class FireAndForgetAsyncClosure : public AsyncClosure {
  42. public:
  43. explicit FireAndForgetAsyncClosure(AsyncInvoker* invoker, FunctorT&& functor)
  44. : AsyncClosure(invoker), functor_(std::forward<FunctorT>(functor)) {}
  45. virtual void Execute() { functor_(); }
  46. private:
  47. typename std::decay<FunctorT>::type functor_;
  48. };
  49. } // namespace rtc
  50. #endif // RTC_BASE_ASYNC_INVOKER_INL_H_