// Start computation thread when page appears on the screen Loaded += (s, e) => { thread = new Thread(ModelRun); isUnloaded = false; thread.Start(); };
// Stop computation thread when page is removed from the screen Unloaded += (s, e) => { isUnloaded = true; thread.Join(); }; }
privatevoidModelRun() { constint N = 1000; double[] y = newdouble[N]; for (int i = 0; i < N; i++) y[i] = Math.Cos(i * Math.PI / 50);
while (!isUnloaded) // Run until page is on the screen { // Data array is updated for (int i = 0; i < N; i++) { y[i] = Math.Cos(i * Math.PI / 50 + phase); } phase += 0.1;
// Render data only if marker graph is not renderind something. // This reduce flickering, but not guarantee that each interation of computations // will be rendered. if (!markers.IsBusy) { // Do not forget to clone changing data before passing to plot double[] data = (double[])y.Clone();
// MarkerGraph.Plot method is thread safe. // Note: PlotY, PlotXY and other similar methods of derived // classes are not thread safe and required Dispatcher.BeginInvoke markers.Plot(null, data, Colors.Red, 5.0); } } } } }
In this sample marker graph shows data that are computed in another thread. Important notes:
Although IsBusy property is used to reduce flicker, that will not guarantee that each interation will be rendered. See DynamicMarkerGraphSample for such scenario.
MarkerGraph.Plot method is thread safe and can be invoked without using Dispatcher.Beginlnvoke.
However it is unsafe to pass concurrenly updated array to Plot method. In this sample array is cloned before passing to Plot.
近期评论