Monday, January 21, 2013

How to check if a WaitHandle is set

Say you have a wait handle of type EventWaitHandle and want to check if it is set or not. To do this call the WaitOne(int) method with a timeout of zero. It will return true if the wait handle is set and false otherwise.

Example


using System;
using System.Threading;
 
namespace ConsoleApp {
    public class Program {
        /// <summary>
        /// Running this program will output
        ///     Wait handle is not set
        ///     Wait handle is set
        /// to the console.
        /// </summary>
        public static void Main(string[] args) {
            var waitHandle = new EventWaitHandle(falseEventResetMode.ManualReset);
 
            Console.WriteLine(waitHandle.WaitOne(0) ? "Wait handle is set" : "Wait handle is not set");
 
            waitHandle.Set();
 
            Console.WriteLine(waitHandle.WaitOne(0) ? "Wait handle is set" : "Wait handle is not set");
        }
    }
}


No comments:

Post a Comment