I have a question about timer in thread?
My code :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Testing testing = new Testing();
Thread thread = new Thread(new ThreadStart(delegate
{
testing.Start();
}));
thread.IsBackground = true;
thread.Start();
}
}
public class Testing
{
System.Threading.Timer timer = null;
public void Start()
{
if (timer == null)
timer = new System.Threading.Timer(timerTick, null, 500, 500);
List<ManualResetEvent> amanual = new List<ManualResetEvent>();
for (int index = 0; index < 10; index++)
{
ManualResetEvent manual = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object context)
{
this.RunningThreadPool(context);
manual.Set();
}
));
amanual.Add(manual);
}
WaitHandle.WaitAll(amanual.ToArray());
Console.WriteLine("Task complete");
}
void timerTick(object sender)
{
Console.WriteLine("Timer running");
}
public void RunningThreadPool(object context)
{
Console.WriteLine("Thread in Threadpool is running...");
}
}
}
And this is result
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Thread in Threadpool is running…
Task complete
Timer running
Timer running
Timer running
Timer running
I have a question that how do timer run before threadpool executed. Except set timer on threadpool. Because i need timer check threads on threadpool.
I’d say that 500ms is quite enough time to complete your work queue, before the Timer even fires once. 10
Console.WriteLinecalls doesn’t amount to much work.Assuming that you’re running a somewhat heavier workload:
The Timer runs its callback in the ThreadPool, so it’s queued after the other work has been queued… i.e. It’s last in the queue. Because you are queueing more items than there are threads in the ThreadPool, and the ThreadPool only spins up new threads under prolonged load, the ThreadPool can’t execute the Timer’s callback in a timely fashion.