简体   繁体   English

使用eventwaithandle进行调度

[英]Scheduling using eventwaithandle

Hi im trying to create an implementation of scheduling using the EventWaitHandle class 您好我试图使用EventWaitHandle类创建一个调度实现

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 阅读代码中的TODO

Boiled down: So i want to be able to schedule an execution for more than int.MaxValue, and manually force execution cross process 简化:所以我希望能够安排执行超过int.MaxValue,并手动强制执行跨进程

Perhaps an easier way of achieving the exact same scenario? 也许是一种更简单的方法来实现完全相同的场景?

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并等待一段时间:

Task.Factory.StartNew(() =>
{
   Thread.Sleep(CalculateSpan());
   // Do something here because the time to wait has passed now
});

After reading the documentation (DOH) i found the solution 阅读文档(DOH)后,我找到了解决方案

    // 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM