This is what the very top level of my unit testing program looks like:
string output;
int returnValue = RunAndTimeAllTests(out output);
System.Console.WriteLine(output);
return returnValue;
Instead of outputting directly to the console everywhere in the program, I output into a string buffer, and then at the very top level output that to the console. This makes unit testing things much easier since I don't have to grab the console output or anything weird like that.
Problem is that when I'm debugging, I'd like to see the console output before the entire program has managed to finish. Exploring the output variable with the debugger is counte-productive since it has all sorts of formatting the debugger ignores.
So my thought was to run a thread at this top level which looks at the output buffer and asynchronously sends new input to the console in a background thread. I'm mindful of thread safety here. I don't want to have to sprinkle the rest of my code with locks. But then I realized with the interesting reference nature of strings, I can do some locking implicitly using reference assignment as an atomic operation. So this is my new code:
string output = "";
bool continueThread = true;
Thread t = new Thread(delegate()
{
do
{
Thread.Sleep(0);
string temp = output;
output = "";
System.Console.Write(temp);
} while (continueThread || !string.IsNullOrEmpty(output));
});
t.Start();
int returnValue = RunAndTimeAllTests(out output);
continueThread = false;
t.Join(1000);
return returnValue;
And let's say that the code inside RunAndTimeAllTests() appends to output like this:
output += "Some message " + "Some other message " + someVariable.ToString();
Am I right in thinking this is thread safe? It gives the right output, but that's no indication. Working through it logically I'm pretty sure there aren't any cases which would result in a race condition. Certainly, since there's no locking, there's no possibility for deadlock. My main concern is the += operator I'm using throughout the code. Are there any weird edge cases where I might end up assigning output = "" in my console thread while the main thread is in the middle of a += operation? Would that screw it up at all?