Blocking and waiting for an event

后端 未结 5 1635
不知归路
不知归路 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:24

    You may also try this:

    class EventWaiter where TEventArgs : EventArgs
    {
        private readonly Action> _unsubHandler;
        private readonly Action> _subHandler;
    
        public EventWaiter(Action> subHandler, Action> unsubHandler)
        {
            _unsubHandler = unsubHandler;
            _subHandler = subHandler;
        }
    
        protected void Handler(object sender, TEventArgs args)
        {
            _unsubHandler.Invoke(Handler);
            TaskCompletionSource.SetResult(args);
        }
    
        public  TEventArgs WaitOnce()
        {
            TaskCompletionSource = new TaskCompletionSource();
            _subHandler.Invoke(Handler);
            return TaskCompletionSource.Task.Result;
        }
    
        protected TaskCompletionSource TaskCompletionSource { get; set; } 
    
    }
    

    Usage:

    EventArgs eventArgs = new EventWaiter((h) => { button.Click += new EventHandler(h); }, (h) => { button.Click -= new EventHandler(h); }).WaitOnce();
    

提交回复
热议问题