Unity does not like it when I multithread, in this case using async for TCP streams. However, I didn’t think I was calling an event on a different thread.
TCP Listener
public delegate void ChatEvent (object sender, ChatEventArgs e);
public delegate void ServerEvent(object sender, ServerEventArgs e);
public class TCPClientListener {
public event ChatEvent OnChatMessage;
public event ServerEvent OnConnect;
private TcpClient tcpClient = new TcpClient ();
private NetworkStream stream;
private void ConnectAsync(){
tcpClient.BeginConnect(host, port, ConnectCallbackAsync, tcpClient);
}
private void ConnectCallbackAsync(IAsyncResult ar){
if(OnConnect != null)
OnConnect(this, new ServerEventArgs("You connected!"));
stream = tcpClient.GetStream();
ReadAsync();
}
private void ReadAsync(){
stream.BeginRead(buffer, 0, bufferSize, ReadCallbackAsync, tcpClient);
}
private void ReadCallbackAsync(IAsyncResult ar){
string message = // convert stream byte[] to string
if(OnChatMessage != null)
OnChatMessage(this, new ChatEventArgs(message));
stream.EndRead();
ReadAsync();
}
}
Unity Chat
using UnityEngine;
public class Chat : Monodevelop{
public Text chatArea; // Initialized via Unity Editor
private TCPClientListener client = new TCPClientListener();
void Awake(){
client.OnConnect += new ServerEvent(OnConnect);
client.OnChatmessage += new ChatEvent(ChatMessage);
ClientStart();
}
private ClientStart(){
client.ConnectAsync();
}
private AppendToChat(string msg){
Debug.Log(msg); // No problem
chatArea.text += "\n" + msg; // get_enabled being called from another thread error
}
private void OnConnect(object sender, ServerEventArgs e){
AppendToChat(e.eventInfo); // No issues
}
private void ChatMessage(object sender, ChatEventArgs e ){
AppendToChat(e.eventInfo); // Culprit of unity error
}
}
I just wrote this as an example so hopefully I didn’t create some error. But if you can follow, my question is this: When I eventually end up calling AppendToChat, exactly which thread am I calling it on?
When OnConnect fires, I append to the chat area with no problems.
When ChatMessage fires, Unity tells me I am calling the chatArea from another thread (via warning: “get_enabled can only be called from the main thread”). So I am not sure what thread I am on with these event listeners.
How then can I avoid calling AppendToChat on another thread ( I’m not even sure what thread it’s on ).