Cancel thread and restart it

前端 未结 2 1277
萌比男神i
萌比男神i 2020-12-20 06:33

When user resizes window some long text should be updated, but if the thread is already running it should be stopped and started over with new width parameter.



        
2条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 06:42

    You should use Microsoft's Reactive Framework (aka Rx) - NuGet System.Reactive.Windows.Threading (for WPF) and add using System.Reactive.Linq; - then you can do this:

        public MainWindow()
        {
            InitializeComponent();
    
            _subscription =
                Observable
                    .FromEventPattern(
                        h => container.SizeChanged += h,
                        h => container.SizeChanged -= h)
                    .Select(e => GetWidth())
                    .Select(w => Observable.Start(
                            () => String.Concat(Enumerable.Range(0, 1000).Select(n => Functionx(w)))))
                    .Switch()
                    .ObserveOnDispatcher()
                    .Subscribe(t => ShowText(t));
        }
    
        private IDisposable _subscription = null;
    

    That's all the code needed.

    This responds to the SizeChanged event, calls GetWidth and then pushes the Functionx to another thread. It uses Switch() to always switch to the latest SizeChanged and then ignores any in-flight code. It pushes the result to the dispatcher and then calls ShowText.

    If you need to close the form or stop the subscription running just call _subscription.Dispose().

    Simple.

提交回复
热议问题