Permalink
Browse files

Tweak sample tick generation to do all work on a background thread

  • Loading branch information...
1 parent 841a144 commit cb07310c7a7361a4d3d7f01cf478444242316e7f @jschementi committed May 8, 2011
@@ -21,6 +21,7 @@
PointFill="White" PointRadius="1"/>
<schementi:Sparkline Grid.Column="2" Grid.Row="0" Margin="0 1"
ShowWatermarks="False" ShowLatestLevel="True"
+ StrokeThickness="1"
Foreground="#FFEEEEEE" />
<schementi:Sparkline Grid.Column="2" Grid.Row="2" Margin="0 1"
ShowWatermarks="True" ShowLatestLevel="True"
@@ -1,31 +1,43 @@
using System;
using System.Linq;
-using System.Windows;
-using System.Windows.Threading;
+using System.Threading;
namespace Schementi.Controls.Demos.Sparkline {
public partial class MainWindow {
+ static readonly object StopLock = new object();
public MainWindow() {
InitializeComponent();
- var sparklines = Grid.Children.OfType<Controls.Sparkline>();
+ var sparklines = Grid.Children.OfType<Controls.Sparkline>().ToArray();
+ var sparklinesCount = sparklines.Length;
+ const int tickTime = 1000/2;
+ var stop = false;
+ WaitCallback tickLoop = wc => {
+ while (true) {
+ var x = 100.0;
+ for (var i = 0; i < sparklinesCount; i++) {
+ var random = new Random();
+ //x = random.Next(100, 200);
+ x = x + (random.NextDouble() * 10 * random.NextDouble() * (random.NextDouble() < 0.5 ? -1 : 1));
+ if (x < 1) x = Math.Abs(x) + 1;
+ Console.WriteLine(x);
- var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.5) };
-
- var x = 100.0;
- timer.Tick += (s, e) => {
- foreach (var sparkline in sparklines) {
- var random = new Random();
- //x = random.Next(100, 200);
- x = x + (random.NextDouble() * 10 * random.NextDouble() * (random.NextDouble() < 0.5 ? -1 : 1));
- if (x < 1) x = Math.Abs(x) + 1;
- Console.WriteLine(x);
- sparkline.AddTimeValue(x);
+ var i1 = i;
+ var x1 = x;
+ Dispatcher.BeginInvoke(new Action(() => sparklines[i1].AddTimeValue(x1)));
+ }
+ Thread.Sleep(tickTime);
+ lock (StopLock) if (stop) return;
}
};
+ Action start = () => ThreadPool.QueueUserWorkItem(tickLoop);
- Loaded += (s, e) => timer.Start();
- Unloaded += (s, e) => timer.Stop();
+ Loaded += (s, e) => start();
+ Unloaded += (s, e) => {
+ lock (StopLock) {
+ stop = true;
+ }
+ };
}
}
}

0 comments on commit cb07310

Please sign in to comment.