async_invoker_inl.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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/critical_section.h"
  15. #include "rtc_base/event.h"
  16. #include "rtc_base/message_handler.h"
  17. #include "rtc_base/ref_counted_object.h"
  18. #include "rtc_base/third_party/sigslot/sigslot.h"
  19. #include "rtc_base/thread.h"
  20. #include "rtc_base/thread_annotations.h"
  21. namespace rtc {
  22. class AsyncInvoker;
  23. // Helper class for AsyncInvoker. Runs a task and triggers a callback
  24. // on the calling thread if necessary.
  25. class AsyncClosure {
  26. public:
  27. explicit AsyncClosure(AsyncInvoker* invoker);
  28. virtual ~AsyncClosure();
  29. // Runs the asynchronous task, and triggers a callback to the calling
  30. // thread if needed. Should be called from the target thread.
  31. virtual void Execute() = 0;
  32. protected:
  33. AsyncInvoker* invoker_;
  34. // Reference counted so that if the AsyncInvoker destructor finishes before
  35. // an AsyncClosure's destructor that's about to call
  36. // "invocation_complete_->Set()", it's not dereferenced after being
  37. // destroyed.
  38. scoped_refptr<RefCountedObject<Event>> invocation_complete_;
  39. };
  40. // Simple closure that doesn't trigger a callback for the calling thread.
  41. template <class FunctorT>
  42. class FireAndForgetAsyncClosure : public AsyncClosure {
  43. public:
  44. explicit FireAndForgetAsyncClosure(AsyncInvoker* invoker, FunctorT&& functor)
  45. : AsyncClosure(invoker), functor_(std::forward<FunctorT>(functor)) {}
  46. virtual void Execute() { functor_(); }
  47. private:
  48. typename std::decay<FunctorT>::type functor_;
  49. };
  50. } // namespace rtc
  51. #endif // RTC_BASE_ASYNC_INVOKER_INL_H_