Unity Asynchronous Socket Client - Threading Problem

Hello, I am trying to make a simple asynchronous socket client and communication goes very well. The problem is I cannot do much with the received information, as it is not processed in the main thread (I am getting this error: “get_isActiveAndEnabled can only be called from the main thread.”).

Is there any simple way how to call the main thread or even simpler way how to do solve this issue?

public Text GameState;

	private void ReceiveCallback(IAsyncResult AR)
	{
		//Check how much bytes are recieved and call EndRecieve to finalize handshake
		int recieved = _clientSocket.EndReceive(AR);

		if(recieved <= 0)
			return;

		//Copy the recieved data into new buffer , to avoid null bytes
		byte[] recData = new byte[recieved];
		Buffer.BlockCopy(_recieveBuffer,0,recData,0,recieved);

		//Process data here the way you want , all your bytes will be stored in recData
		string incomingMsg = "Received: " + Encoding.ASCII.GetString(recData);

		Debug.Log(incomingMsg);

		//THIS DOES NOT WORK
	GameState.text = incomingMsg;


		//Start receiving again
		_clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
	}

Watch the line: GameState.text = incomingMsg;

I am trying to set UI.Text field’s value to no avail.

Well I do this already and I made a tasker which was improved a little in this thread Multi-threading safely - Questions & Answers - Unity Discussions

As Bunny83 said,"Keep in mind that you can’t read isActiveAndEnabled or any other property from Unity components inside class constructors or fieldinitializer of MonoBehaviour classes. "

You cannot try to change a unity object’s value in your socket’s thread.
I made this mistake just as you and got the same error code.

You can try to claim a static variable in the MonoBehaviour class,set incomingMsg to this variable and then change the unity object’s value,which in your conditon is “GameState.text”,to the variable through a MonoBehaviour method such as Update or something else.