This sample code shows how to assign a ThreadPool thread so it can execute at a specified Interval or instantly.
using System;
using System.Threading;
public class ThreadManager : System.Windows.Forms.Form
{
private RegisteredWaitHandle handle = null
private AutoResetEvent ev = null;
/// <summary>
/// Initialize Threadpool timer function to fetch new requests in the certain time interval.
/// </summary>
public void InitializeMasterThread()
{
// Time Interval MasterThread will be executed
TimeSpan timeSpan = TimeSpan.FromSeconds(Double.Parse(timeSlot));
// Create AutoResetEvent
ev = new AutoResetEvent(false);
// Start timer thread
handle = ThreadPool.RegisterWaitForSingleObject(
ev,
new WaitOrTimerCallback(CallFun),
"SomeState",
2000,
false
);
}
/// <summary>
/// Helper method - To avoid delay to call MasterThread.
/// Used in first request.
/// </summary>
public void StartThread()
{
ev.Set();
}
private void CallFun(object state, bool activated)
{
// Do you work here and this work will be called again and again after certain time interval
//If you want to Unregister timer thread from ThreadPool then see the commented code below
// if(handle != null)
// handle.Unregister(null);
//After Unregiter you have to call InitializeMasterThread Again to register it.
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Call Initilize function to register wait handle.
InitializeMasterThread();
//Call function which will call CallFun Inside Thread Instant besides wait for timeout
StartThread();
}
}