Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Restarting Tasks

$
0
0

I have a ListBox with 100 custom TextBlocks. 

I need each to execute long function on a different thread but to restart that function if listbox is resized. Final function will to something more useful than just counting.

public class MyTextBlock : TextBlock { FrameworkElement _container; Task mytask; private CancellationTokenSource tokenSource = new CancellationTokenSource(); private CancellationToken ct = new CancellationToken(); public MyTextBlock() { this.Loaded += new RoutedEventHandler(MyTextBlock_Loaded); this.SizeChanged += new SizeChangedEventHandler(MyTextBlock_SizeChanged); } void MyTextBlock_Loaded(object sender, RoutedEventArgs e) { ct = tokenSource.Token; runtask(); } void MyTextBlock_SizeChanged(object sender, SizeChangedEventArgs e) { changed(); } private void changed() { if (mytask == null) {

runtask();

return;

} if (mytask.IsCompleted) runtask(); else { tokenSource.Cancel(); //cancel restarts the function } } private void runtask() { int width = (int)this.Width; string text = ""; mytask= Task.Factory.StartNew (() => { int i; for (i = 0; i < 1000; i++) { Thread.Sleep(50); this.Dispatcher.BeginInvoke(new Action(() => { this.Text = mytask.Id + " : " + i.ToString(); }), System.Windows.Threading.DispatcherPriority.SystemIdle); if (ct.IsCancellationRequested){ //restarting tokenSource.Dispose(); tokenSource = new CancellationTokenSource(); ct = tokenSource.Token; i = 0; } } }, tokenSource.Token); } }


This code starts works but it starts counting on 12 TextBlocks, and then every next takes more time to start, some TextBlocks don't update on resize, and thread IDs change on resize as if new thread are created each time. What is wrong?


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>