[c++] Cross thread communications – Part II

Recently I’ve been playing around with managed C++ and the .net framework. As usual I have one thread wanting to instruct a separate GUI thread to perform some task. In .net world with the help of delegates (glorified function pointers) this behaviour is easy.

First define the function to call:

///  update text box text from another thread
void MyGuiClass::updateText( System::String^ text ) {
	// show text
}

then define a delegate:

public delegate void GuiUpdateTextDelegate( );

and finally invoke the delegate from another thread:

BeginInvoke(
	gcnew GuiUpdateTextDelegate(
		this, &MyGuiClass::updateText, gcnew Systen::String("new text")
	)
);

While I’ve used BeginInvoke here, you should be aware that there is also an Invoke method. Invoke will wait until the delegate has been invoked, while BeginInvoke won’t and is asynchronous.