Thread abbrechen und neu starten

Wenn der Benutzer die Fenstergröße ändert, sollte ein Teil des Langtexts aktualisiert werden. Wenn der Thread jedoch bereits ausgeführt wird, sollte er angehalten und mit dem neuen Parameter width neu gestartet werden.

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
              };
           });
        }

Was jetzt passiert, ist, wenn ich die Größe des Fensters verändere und sehe, dass der Text die nächsten Sekunden iterativ aktualisiert wird, als ob alte Threads nicht abgebrochen worden wären. Was mache ich falsch?

Antworten auf die Frage(1)

Ihre Antwort auf die Frage