AsyncCaller :: FYI

I use the AsyncUpdater quite a bit and was running into problems with ambiguous usage of AsyncUpdater when my inheritance hierarchies were getting complicated. I created a template class that allows member functions to be called asynchronously:

#include "../../juce_appframework/events/juce_AsyncUpdater.h"
#include "../../juce_core/threads/juce_CriticalSection.h"
#include "../../juce_core/containers/juce_Array.h"
#include "../../juce_core/basics/juce_Singleton.h"

template <class ElementType>
class AsyncCaller : public AsyncUpdater
{
private:
	Array <void (ElementType::*) (void), CriticalSection> functions;
	Array <ElementType *, CriticalSection> classes;

public:
	AsyncCaller () {}

	~AsyncCaller()
	{
		cancelPendingUpdate ();
	}

	void callFunctionAsynchronously (void (ElementType::*function) (void), ElementType * element)
	{
		classes.add (element);
		functions.add (function);
		triggerAsyncUpdate ();
	}

private:

	void handleAsyncUpdate ()
	{
		while (functions.size() > 0)
		{
			(classes.getUnchecked (0)->*(functions.getUnchecked (0))) ();
			classes.remove(0);
			functions.remove(0);
		}
	}
};

To use, create an AsyncCaller in your class and create your callback function:

class Router
{
private:
	AsyncCaller <Router> asyncCaller;

   void handleAsyncUpdate ();
};

void Router::handleAsyncUpdate ()
{

}

To use, call the callFunctionAsynchronously function:

asyncCaller.callFunctionAsynchronously (&Router::handleAsyncUpdate, this);