代码之家  ›  专栏  ›  技术社区  ›  Lars Nielsen

使用事件等待句柄进行调度

  •  0
  • Lars Nielsen  · 技术社区  · 11 年前

    嗨,我正在尝试使用EventWaitHandle类创建调度的实现

    以以下示例为例:

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

    阅读代码中的TODO

    简单地说:所以我希望能够调度一个超过int.MaxValue的执行,并手动强制跨流程执行

    也许是实现完全相同场景的更简单方法?

    2 回复  |  直到 11 年前
        1
  •  1
  •   Clint    11 年前

    如果你所追求的只是等待一段时间,然后再做一些你可以使用的事情:

    • Thread.Sleep
      • 不建议这样做,因为这会阻塞线程,通常被认为是不好的做法(除非你在一个单独的线程上,否则你可以阻塞)
    • Timer
      • 最常见的解决方案是,它支持异步触发定时器事件,这样就不会干扰主线程等。

    你也可以旋转一个新的线程/ Task 等待一段时间后再做某事:

    Task.Factory.StartNew(() =>
    {
       Thread.Sleep(CalculateSpan());
       // Do something here because the time to wait has passed now
    });
    
        2
  •  1
  •   Lars Nielsen    11 年前

    在阅读了文档(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);