Reentrant of ASP. NET timer callback method
- 2021-09-12 00:54:13
- OfStack
Without saying much, please look at the code:
using System;
using System.Collections.Generic;
using System.Text;
namespace NET.MST.Sixth.Reenter
{
class Reenter
{
// Static members used to cause thread synchronization problems
private static int TestInt1=0;
private static int TestInt2 = 0;
private static object locko = new object();
static void Main(string[] args)
{
Console.WriteLine("System.Timers.Timer Callback method reentrant test: ");
TimersTimerReenter();
// Make sure that the callback method that has already started has a chance to end
System.Threading.Thread.Sleep(2 * 1000);
Console.WriteLine("System.Threading.Timer Callback method reentrant test: ");
ThreadingTimerReenter();
Console.Read();
}
/// <summary>
/// Display System.Timers.Timer Callback method reentrant of
/// </summary>
static void TimersTimerReenter()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 100; //100 Milliseconds
timer.Elapsed += TimersTimerHandler;
timer.Start();
System.Threading.Thread.Sleep(2 * 1000); // Run 2 Seconds
timer.Stop();
}
/// <summary>
/// Display System.Threading.Timer Callback method reentrant of
/// </summary>
static void ThreadingTimerReenter()
{
//100 Milliseconds
using (System.Threading.Timer timer = new System.Threading.Timer
(new System.Threading.TimerCallback(ThreadingTimerHandler), null, 0, 100))
{
System.Threading.Thread.Sleep(2 * 1000); // Run 2 Seconds
}
}
/// <summary>
/// System.Timers.Timer Callback method of
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private static void TimersTimerHandler(object sender,EventArgs args)
{
lock (locko)
{
Console.WriteLine(" Test integer: " + TestInt1.ToString());
// Sleep 10 Seconds to ensure method reentry
System.Threading.Thread.Sleep(300);
TestInt1++;
Console.WriteLine(" Self-increasing 1 Post-test integer: " + TestInt1.ToString());
}
}
/// <summary>
/// System.Threading.Timer Callback method of
/// </summary>
/// <param name="state"></param>
private static void ThreadingTimerHandler(object state)
{
lock (locko)
{
Console.WriteLine(" Test integer: " + TestInt2.ToString());
// Sleep 10 Seconds to ensure method reentry
System.Threading.Thread.Sleep(300);
TestInt2++;
Console.WriteLine(" Self-increasing 1 Post-test integer: " + TestInt2.ToString());
}
}
}
}