1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef nsThreadSyncDispatch_h_ 8 #define nsThreadSyncDispatch_h_ 9 10 #include "nsThreadUtils.h" 11 #include "LeakRefPtr.h" 12 #include "mozilla/DebugOnly.h" 13 14 class nsThreadSyncDispatch : public mozilla::Runnable 15 { 16 public: nsThreadSyncDispatch(nsIThread * aOrigin,already_AddRefed<nsIRunnable> && aTask)17 nsThreadSyncDispatch(nsIThread* aOrigin, already_AddRefed<nsIRunnable>&& aTask) 18 : mOrigin(aOrigin) 19 , mSyncTask(mozilla::Move(aTask)) 20 { 21 } 22 IsPending()23 bool IsPending() 24 { 25 return !!mSyncTask; 26 } 27 28 private: Run()29 NS_IMETHOD Run() override 30 { 31 if (nsIRunnable* task = mSyncTask.get()) { 32 mozilla::DebugOnly<nsresult> result = task->Run(); 33 MOZ_ASSERT(NS_SUCCEEDED(result), 34 "task in sync dispatch should not fail"); 35 // We must release the task here to ensure that when the original 36 // thread is unblocked, this task has been released. 37 mSyncTask.release(); 38 // unblock the origin thread 39 mOrigin->Dispatch(this, NS_DISPATCH_NORMAL); 40 } 41 return NS_OK; 42 } 43 44 nsCOMPtr<nsIThread> mOrigin; 45 // The task is leaked by default when Run() is not called, because 46 // otherwise we may release it in an incorrect thread. 47 mozilla::LeakRefPtr<nsIRunnable> mSyncTask; 48 }; 49 50 #endif // nsThreadSyncDispatch_h_ 51