On page 47 of Wrox's "C# Threading Handbook" in the code listing for the GenerateText method, you will see that each string builder append line starts with sb.Length. Just remove the sb.Length and the code will run fine.
If anyone knows some one at Apress, who handles the errata for their old wrox book, I would like to be able to put this errata in a more centralized location.
Thanks
Here's the code listing.
using
System;
using
System.Threading;
using
System.Text;
namespace
TimerExample
{
class TimerExample
{
private string message;
private static Timer tmr;
private static bool complete;
static void Main(string[] args)
{
TimerExample obj = new TimerExample();
Thread t = new Thread(new ThreadStart(obj.GenerateText));
t.Start();
TimerCallback tmrCallBack = new TimerCallback(obj.GetText);
tmr =
new Timer(tmrCallBack, null, TimeSpan.Zero, TimeSpan.FromSeconds(2));
do
{
if (complete)
break;
}
while (true);
Console.WriteLine("Exiting Main");
Console.ReadLine();
}
public void GenerateText()
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i < 200; i++)
{
Thread.Sleep(100);
sb.Append(
"This is Line ");
sb.Append(i.ToString());
sb.Append(System.
Environment.NewLine);
}
message = sb.ToString();
}
public void GetText(object state)
{
if (message == null)
return;
Console.WriteLine("Message is :");
Console.WriteLine(message);
tmr.Dispose();
complete =
true;
}
}
}