Just when you think you understand something ...
I recently wrote some code that I have distilled down to the example below. Can anyone tell me if it is safe? It appears to be. I get the expected output (including two calls to construction of the StringBuilder). But my machine is a single CPU/single core, so maybe I am just fluking it by not seeing 'proper' multi-threaded behaviour.
Any advice or pointers to good articles on this would be very much appreciated.
using System;
using System.Text;
using System.Threading;
namespace ThreadingTest
{
class Program
{
static void Main()
{
Thread thread1 = new Thread( new ThreadStart( ProcessEntry ) );
Thread thread2 = new Thread( new ThreadStart( ProcessEntry ) );
thread1.Name = "0";
thread2.Name = "10";
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.ReadLine();
}
private static void ProcessEntry()
{
Console.WriteLine( "{0} constructing StringBuilder", Thread.CurrentThread.Name );
StringBuilder sb = new StringBuilder( Thread.CurrentThread.Name + ":" );
for( int i = 0; i < 10; ++i )
{
int offset = Int32.Parse( Thread.CurrentThread.Name );
sb.AppendFormat( "{0} ", offset + i );
Thread.Sleep( 100 );
Console.WriteLine( sb.ToString() );
Thread.Sleep( 500 );
}
Console.WriteLine();
}
}
}