SameProcessMessageQueue.cpp (1831B)
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 file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "SameProcessMessageQueue.h" 8 9 #include "nsThreadUtils.h" 10 11 using namespace mozilla; 12 using namespace mozilla::dom; 13 14 SameProcessMessageQueue* SameProcessMessageQueue::sSingleton; 15 16 SameProcessMessageQueue::SameProcessMessageQueue() = default; 17 18 SameProcessMessageQueue::~SameProcessMessageQueue() { 19 // This code should run during shutdown, and we should already have pumped the 20 // event loop. So we should only see messages here if someone is sending 21 // messages pretty late in shutdown. 22 NS_WARNING_ASSERTION(mQueue.IsEmpty(), 23 "Shouldn't send messages during shutdown"); 24 sSingleton = nullptr; 25 } 26 27 void SameProcessMessageQueue::Push(Runnable* aRunnable) { 28 mQueue.AppendElement(aRunnable); 29 NS_DispatchToCurrentThread(aRunnable); 30 } 31 32 void SameProcessMessageQueue::Flush() { 33 const nsTArray<RefPtr<Runnable>> queue = std::move(mQueue); 34 for (size_t i = 0; i < queue.Length(); i++) { 35 queue[i]->Run(); 36 } 37 } 38 39 /* static */ 40 SameProcessMessageQueue* SameProcessMessageQueue::Get() { 41 if (!sSingleton) { 42 sSingleton = new SameProcessMessageQueue(); 43 } 44 return sSingleton; 45 } 46 47 SameProcessMessageQueue::Runnable::Runnable() : mDispatched(false) {} 48 49 NS_IMPL_ISUPPORTS(SameProcessMessageQueue::Runnable, nsIRunnable) 50 51 nsresult SameProcessMessageQueue::Runnable::Run() { 52 if (mDispatched) { 53 return NS_OK; 54 } 55 56 SameProcessMessageQueue* queue = SameProcessMessageQueue::Get(); 57 queue->mQueue.RemoveElement(this); 58 59 mDispatched = true; 60 return HandleMessage(); 61 }