Throttling Events and Locking Methods

前端 未结 5 2037
小鲜肉
小鲜肉 2021-02-04 18:15

Let\'s pretend I have something like this:


And something like this:

publ         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 18:49

    I think a simpler and reusable way to solve your problem might actually be async/await-based rather than RX-based. Check out the single threaded EventThrottler class implementation I got as an answer to my 'Is there such a synchronization tool as “single-item-sized async task buffer”?' question. With that you can rewrite your DoWork() method as simply:

    private void DoWork()
    {
        EventThrottler.Default.Run(async () =>
        {
            await Task.Delay(1000);
            //do other stuff
        });
    }
    

    and call it every time your text changes. No RX required. Also, if you are already using WinRT XAML Toolkit - the class is in there.

    Here's a copy of the throttler class code as a quick reference:

    public class EventThrottler
    {
        private Func next = null;
        private bool isRunning = false;
    
        public async void Run(Func action)
        {
            if (isRunning)
                next = action;
            else
            {
                isRunning = true;
    
                try
                {
                    await action();
    
                    while (next != null)
                    {
                        var nextCopy = next;
                        next = null;
                        await nextCopy();
                    }
                }
                finally
                {
                    isRunning = false;
                }
            }
        }
    
        private static Lazy defaultInstance =
            new Lazy(() => new EventThrottler());
        public static EventThrottler Default
        {
            get { return defaultInstance.Value; }
        }
    }
    

提交回复
热议问题