Fun with the ThreadPool : Find the bug
关于下面的这个小程序的问题, 想听听大家的看法 ;)
程序引自: http://ayende.com/Blog/archive/2007/01/12/FunWithTheThreadPool2FindTheBug.aspx
这是关于程序的一些说明:
The timer wakes a set of services that need to process input.
To avoid re-entrancy issues, I used synchornized methods.
Some services does non trivial amount of work.
class Program
{
static int count = 0;
static Timer timer;
static void Main(string[] args)
{
timer = new Timer(delegate
{
int temp = Interlocked.Increment(ref count);
ThreadPool.QueueUserWorkItem(DoLengthyWork, temp);
ThreadPool.QueueUserWorkItem(ReportStatus, temp);
},null,100,100);
Console.ReadKey();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DoLengthyWork(object counter)
{
//do stuff that may fail on re-entry
Thread.Sleep(1500);
Console.WriteLine("Finished lengthy work: {0}", counter);
}
public static void ReportStatus(object counter)
{
Console.WriteLine("Reporting status: {0}", counter);
}
}