If your application is doing asynchronous things, for instance a form has a callback function from a class receiving say some communications, then you will need to deal with calls to it in a thread safe way. The reason is that forms run on a single thread, but events in the other class will not necessarily be on the same thread. So to deal with this…

When you don't need to pass any arguments


	//DEAL WITH IN THREAD SAFE WAY
	void HandleEvent_MultiThreaded(void)
	{
		//WE MAY NOT BE ON THE SAME THREAD AS THIS ACTUAL FORM, SO HANDLE CORRECTLY
		if (this->txtConnectionStatus->InvokeRequired)							//Change txtConnectionStatus to be some object on your form (or just use this->InvokeRequired if its possible)
			this->Invoke(gcnew MethodInvoker(this, &frmMain::HandleEvent));		//Change frmMain if necessary to your forms class
		else
			HandleEvent();
	}

	private: void HandleEvent (void)
	{
		txtConnectionStatus->Text = "Hello";
		//...
	}

When you do need to pass arguments


	//Declare a delegate
	private: delegate void HandleEvent_Del (int Type, array<unsigned char> ^RxData, int RxLength);

	//DEAL WITH IN THREAD SAFE WAY
	void HandleEvent_MultiThreaded(int Type, array<unsigned char> ^RxData, int RxLength)
	{
		//WE MAY NOT BE ON THE SAME THREAD AS THIS ACTUAL FORM, SO HANDLE CORRECTLY
		if (this->txtConnectionStatus->InvokeRequired)						//Change txtConnectionStatus to be some object on your form (or just use this->InvokeRequired if its possible)
			this->Invoke(gcnew HandleEvent_Del(this, &frmMain::HandleEvent),Type, RxData, RxLength);	//Change frmMain if necessary to your forms class
		else
			HandleEvent(Type, RxData, RxLength);
	}

	private: void HandleEvent (int Type, array ^RxData, int RxLength)
	{
		txtConnectionStatus->Text = Convert::ToString(Type);
		//...
	}
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published.