- Home /
Multithreaded String Log Doesn't Update
I have a Log class that I use to update an on screen display. It's log function is called both from the main thread as well as the thread I use to run my networking code.
public void Log(string NewMsg)
{
lock(LogText)
{
string NewLine = NewMsg + "\n";
LogText += NewLine;
NeedsUpdate = true;
}
}
public void UpdateLogDisplay ()
{
lock(LogText)
{
if (NeedsUpdate)
{
ErrorLogDisplay.text = LogText;
NeedsUpdate = false;
}
}
}
The code below is where the Log function above breaks. The first two calls work as well as several other calls before them, the third does not. I'm getting the impression that it is the second call that breaks something. The code below, as well as many other calls to Log, are being called on a thread that runs my networking code.
Display.Log("Receive Error: " + ReceiveError.ToString());
Display.Log(System.Text.Encoding.UTF8.GetString(ReceivedDataBuffer));
Display.Log("!!");
If I put a Debug.Log(NewMsg)
inside the lock statement in Log
it prints what I would expect. If, after LogText += NewLine
, I put Debug.Log(LogText)
, the LogText
hasn't been updated.
I'm not super experienced with threads so I have no idea why this happens. Any help is greatly appreciated.