Threading.Timer
internal sealed class UnSafelTimer
{
private static Timer timer;
private static object unsafel_lock = new object();
private static int count = 0;
private static Stopwatch watch = new Stopwatch();
private static void ExcuteMethod(object state)
{
Thread.CurrentThread.IsBackground = true;
int temp;
lock (unsafel_lock)
{
count++;
temp = count;
}
if (temp == 10)
{
timer.Dispose();
watch.Stop();
}
if (temp < 10)
Console.WriteLine("NOW:{0}", temp);
else
Console.WriteLine("NOW:{0},-------Timer已经耗时{1}毫秒了", temp, watch.ElapsedMilliseconds);
Thread.Sleep(1000);
}
public static void Start()
{
watch.Start();
timer = new Timer(ExcuteMethod, null, 1000, 10);
}
}
Timer.Timer
internal sealed class SafelTimer
{
private static System.Timers.Timer timer;
private static object unsafel_lock = new object();
private static int count = 0;
private static Stopwatch watch = new Stopwatch();
public static void Start()
{
timer = new System.Timers.Timer();
timer.Interval = 10;
timer.Elapsed += ExcuteMethod;
timer.Start();
}
private static void ExcuteMethod(object sender, System.Timers.ElapsedEventArgs e)
{
Thread.CurrentThread.IsBackground = true;
int temp;
lock (unsafel_lock)
{
count++;
temp = count;
}
if (temp == 10)
{
timer.Dispose();
watch.Stop();
}
if (temp < 10)
Console.WriteLine("NOW:{0}", temp);
else
Console.WriteLine("NOW:{0},-------Timer已经耗时{1}毫秒了", temp, watch.ElapsedMilliseconds);
Thread.Sleep(1000);
}
}