简体   繁体   English

只要没有触发其他事件,就等待事件

[英]Wait for event so long as other event hasn't fired

I have an async method where I would like to block execution until 2 seconds after the OnLeave event of a control is fired, but only if the OnEnter event is not fired in the meantime. 我有一个异步方法,在此之前,我希望在执行控件的OnLeave事件后2秒之前阻止执行,但OnLeave是同时未触发OnEnter事件。

In other words, if the OnLeave event is fired and then OnEnter fires 1 sec after, it should wait for another OnLeave + another 2 seconds without the OnEnter firing again before returning back to my method. 换句话说,如果触发了OnLeave事件,然后在1秒钟后触发了OnEnter ,则它应等待另一个OnLeave + 2秒,而不会再次触发OnEnter ,然后再返回我的方法。

This should also implement a timeout and I looked at using a Task.WaitAll() with a timeout, but just not quite sure how to do the first part because of the dependency on both events. 这也应该实现一个超时,并且我研究了如何使用带有超时的Task.WaitAll(),但是由于这两个事件的依赖性,我不太确定如何执行第一部分。

Can anyone provide some suggestions? 谁能提供一些建议?

Try this: 尝试这个:

public class Control {
    public EventHandler OnEnter;
    public EventHandler OnLeave;

    public void TriggerEnter() {
        if (OnEnter != null) {
            OnEnter(null, EventArgs.Empty);
        }
    }

    public void TriggerLeave() {
        if (OnLeave != null) {
            OnLeave(null, EventArgs.Empty);
        }
    }
}

class Program {
    public static EventHandler OnBufferedEvent;

    static void Main(string[] args) {
        bool hasEntered = false;
        Timer timer = new Timer(2000);
        OnBufferedEvent += (sender, eventArgs) => Console.WriteLine("My buffered event has fired");

        timer.Elapsed += (sender, e) =>{
            if (!hasEntered) {
                if (OnBufferedEvent != null) {
                    OnBufferedEvent(null, EventArgs.Empty);
                }
            }
        };

        Control control = new Control {
            OnEnter = (sender, eventArgs) => {
                hasEntered = true;
                Console.WriteLine("On enter event has fired");
            },
            OnLeave = (sender, eventArgs) => {
                hasEntered = false;
                timer.Start();
                Console.WriteLine("On leave event has fired");
            }
        };

        control.TriggerLeave();
        Thread.Sleep(1000);
        control.TriggerEnter();
        Thread.Sleep(100);
        control.TriggerLeave();
        Thread.Sleep(2500);
    }
}

Another, more exotic solution, would be using Rx to buffer events and do observation logic on them. 另一个更奇特的解决方案是使用Rx缓冲事件并对其进行观察逻辑。

This link provides some more explanations but you will have to create observable collections out of both Enter and Leave events and mix them up together. 链接提供了更多解释,但是您将必须从Enter和Leave事件中创建可观察的集合,并将它们混合在一起。 Not a trivial task. 这不是一件微不足道的任务。

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

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