Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

int myWidth;
private CancellationTokenSource tokenSource2 = new CancellationTokenSource();
private CancellationToken ct = new CancellationToken();

void container_Loaded(object sender, RoutedEventArgs e)
{
  ct = tokenSource2.Token;
  MyFunction();
}

        void container_SizeChanged(object sender, SizeChangedEventArgs e)
        {
          if (tokenSource2.Token.IsCancellationRequested)
            MyFunction();
          else
            tokenSource2.Cancel();
        }

        void MyFunction()            
        {
           myWidth = GetWidth();
           Task.Factory.StartNew(() =>
           {  
              string s;    
              for (int i=0;i<1000,i++){
                  s=s+Functionx(myWidth);
                  ct.ThrowIfCancellationRequested();
              }
              this.Dispatcher.BeginInvoke(new Action(() => { 
                   ShowText(s); 
              }));
           },tokenSource2.Token)
           .ContinueWith(t => {
              if (t.IsCanceled)
              {
                tokenSource2 = new CancellationTokenSource(); //reset token
                MyFunction(); //restart
              };
           });
        }

What now is happening is when I resize window I see text iteratively updating next several seconds as if old threads were not canceled. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
343 views
Welcome To Ask or Share your Answers For Others

1 Answer

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<SizeChangedEventHandler, SizeChangedEventArgs>(
                    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...