Blocking and waiting for an event

后端 未结 5 1638
不知归路
不知归路 2020-12-15 03:45

It sometimes want to block my thread while waiting for a event to occur.

I usually do it something like this:

private AutoResetEvent _autoResetEvent          


        
5条回答
  •  被撕碎了的回忆
    2020-12-15 04:22

    I think like these should work, didn't tried just coded.

    public class EventWaiter where T : EventArgs
    {
        private System.Threading.ManualResetEvent manualEvent;
    
        public EventWaiter(T e)
        {
            manualEvent = new System.Threading.ManualResetEvent(false);
            e += this.OnEvent;
        }
    
        public void OnEvent(object sender, EventArgs e)
        {
            manualEvent.Set();
        }
    
        public void WaitOne()
        {
            manualEvent.WaitOne();
        }
    
        public void Reset()
        {
            manualEvent.Reset();
        }
    }
    

    Didn't thought about too much, but can't figure out how to make it isolated from the EventArgs.

    Take a look at the MSDN ManualResetEvent and you will discover that you can kind of chain the waits and so some weird stuff.

提交回复
热议问题