Mega Code Archive

 
Categories / C# Tutorial / Thread
 

Queuing a task for execution by ThreadPool threads, with the RegisterWaitForSingleObject method

using System; using System.Threading; public class MyValue {     public RegisteredWaitHandle Handle = null;     public string OtherInfo = "default"; } public class Example {     public static void Main(string[] args) {         AutoResetEvent ev = new AutoResetEvent(false);         MyValue ti = new MyValue();         ti.OtherInfo = "My task";         ti.Handle = ThreadPool.RegisterWaitForSingleObject(             ev,             new WaitOrTimerCallback(WaitProc),             ti,             1000,             false         );         Thread.Sleep(300);         ev.Set();         Thread.Sleep(100);     }     public static void WaitProc(object state, bool timedOut) {         MyValue ti = (MyValue) state;         if(timedOut){             Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",                 ti.OtherInfo,                  Thread.CurrentThread.GetHashCode().ToString(),                  "TIMED OUT"             );         }         if (ti.Handle != null){             ti.Handle.Unregister(null);         }         Console.WriteLine("WaitProc( {0} ) executes on thread {1}; cause = {2}.",                 ti.OtherInfo,                  Thread.CurrentThread.GetHashCode().ToString(),                  "SIGNALED"         );     } }