Handling both time-outs and signals with a WaitOrTimerCallback delegate. : AutoResetEvent « Thread « C# / CSharp Tutorial






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(ti.OtherInfo);
        }
        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"
        );
    }
}








20.24.AutoResetEvent
20.24.1.AutoResetEvent in action
20.24.2.Register Wait handle for auto reset event
20.24.3.Handling both time-outs and signals with a WaitOrTimerCallback delegate.