Question

Hi im trying to create an implementation of scheduling using the EventWaitHandle class

Take the following example:

// Program 1
static void Main(string[] args)
{
    EventWaitHandle wh = new EventWaitHandle(false,EventResetMode.ManualReset,"MyCrossProcessEventHandle");
    wh.Set();
}

// Program 2
static void Main(string[] args)
{
    EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.ManualReset, "MyCrossProcessEventHandle");

    while (true)
    {
        var span = CalculateSpan();

        wh.WaitOne(span);

        // TODO Implement check, why did execution proceed? 
        // timeout ocurred
        // OR
        // Eventhandle was set
        //
        // if timeout occured
        // break the current iteration loop (And thereby calculate a new timeout)
        //
        // if event.set
        // continue execution




        // SNIP SNIP - More code here
    }
}

private static int CalculateSpan()
{
    DateTime datetoRun = new DateTime(2020,01,01,00,00,00);

    var span = datetoRun - DateTime.Now;

    if (span.TotalMilliseconds >= int.MaxValue)
    {
        return int.MaxValue;
    }

    return (int)span.TotalMilliseconds;
}

READ THE TODO IN THE CODE

Boiled down: So i want to be able to schedule an execution for more than int.MaxValue, and manually force execution cross process

Perhaps an easier way of achieving the exact same scenario?

Was it helpful?

Solution 2

After reading the documentation (DOH) i found the solution

    // Summary:
    //     Blocks the current thread until the current System.Threading.WaitHandle receives
    //     a signal, using a 32-bit signed integer to specify the time interval.
    //
    // SNIP SNIP
    //
    // Returns:
    //     true if the current instance receives a signal; otherwise, false.
    //
    // SNIP SNIP
    public virtual bool WaitOne(int millisecondsTimeout);

OTHER TIPS

If all you're after is waiting for a set period of time before doing something you could use:

  • Thread.Sleep
    • Not recommended though as this blocks the thread and is generally considered bad practice (unless you're on a separate thread you can block)
  • Timer
    • The most common solution as it supports firing a timer event asynchronously so it doesn't interfere with your main thread etc.

You could also just spin up a new thread / Task and wait for a set period before doing something:

Task.Factory.StartNew(() =>
{
   Thread.Sleep(CalculateSpan());
   // Do something here because the time to wait has passed now
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top