RegisterWaitForSingleObject in ThreadPool

This sample code shows how to assign a ThreadPool thread so it can execute at a specified Interval or instantly.

using System;
public class ThreadManager : System.Windows.Forms.Form
private RegisteredWaitHandle handle = null
private AutoResetEvent ev = null;
/// 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(
new WaitOrTimerCallback(CallFun),
/// <summary>
/// Helper method - To avoid delay to call MasterThread.
/// Used in first request.
/// </summary>
public void StartThread()
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.
//Call function which will call CallFun Inside Thread Instant besides wait for timeout

Up Next
    Ebook Download
    View all
    View all