1 #include "stdafx.h" 2 #include <algorithm> 3 #include "NotificationManager.h" 4 RegisterNotificationListener(shared_ptr<INotificationListener> notificationListener)5void NotificationManager::RegisterNotificationListener(shared_ptr<INotificationListener> notificationListener) 6 { 7 auto lock = _lock.AcquireSafe(); 8 9 for(weak_ptr<INotificationListener> listener : _listeners) { 10 if(listener.lock() == notificationListener) { 11 //This listener is already registered, do nothing 12 return; 13 } 14 } 15 16 _listeners.push_back(notificationListener); 17 } 18 CleanupNotificationListeners()19void NotificationManager::CleanupNotificationListeners() 20 { 21 auto lock = _lock.AcquireSafe(); 22 23 //Remove expired listeners 24 _listeners.erase( 25 std::remove_if( 26 _listeners.begin(), 27 _listeners.end(), 28 [](weak_ptr<INotificationListener> ptr) { return ptr.expired(); } 29 ), 30 _listeners.end() 31 ); 32 } 33 SendNotification(ConsoleNotificationType type,void * parameter)34void NotificationManager::SendNotification(ConsoleNotificationType type, void* parameter) 35 { 36 vector<weak_ptr<INotificationListener>> listeners; 37 { 38 auto lock = _lock.AcquireSafe(); 39 CleanupNotificationListeners(); 40 listeners = _listeners; 41 } 42 43 //Iterate on a copy without using a lock 44 for(weak_ptr<INotificationListener> notificationListener : listeners) { 45 shared_ptr<INotificationListener> listener = notificationListener.lock(); 46 if(listener) { 47 listener->ProcessNotification(type, parameter); 48 } 49 } 50 } 51