Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

c# - Cancel thread and restart it

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...