Csharp-Data-Visualization
Csharp-Data-Visualization copied to clipboard
WPF: What is the best way to achieve continuous rendering?
Remove the Timer from the "MainWindow" and replace it with.
private void Checkbox1_Checked(object sender, RoutedEventArgs e) => CompositionTarget.Rendering += CompositionTarget_Rendering;
private void Checkbox1_Unchecked(object sender, RoutedEventArgs e) => CompositionTarget.Rendering -= CompositionTarget_Rendering;
private void CompositionTarget_Rendering(object? sender, EventArgs e)
{
SkElement1.InvalidateVisual();
}
Hi @trmcnealy,
Thanks for this suggestion! I'm not very familiar with the pros and cons of using CompositionTarget.Rendering
vs a timer for drawing graphics. A quick search advises timers are superior for limiting frame rate or implementing physics simulations where models should progress at a standard rate. This may favor the use of timers since many of the other projects on https://swharden.com/csdv/ (e.g., boids) would benefit from a constant speed.
EDIT: A more extensive search reveals some people recommend the opposite!
This discussion is worth including on the page though, so I'll create a new page comparing/contrasting these methods and link to it from all the relevant WPF pages.
Note that the web page being referenced is
- https://swharden.com/csdv/maui.graphics/quickstart-wpf/
which references project code that lives here:
https://github.com/swharden/Csharp-Data-Visualization/blob/0c7683d307320b922d64a6fd55f890c20d17950d/projects/maui-graphics/QuickstartWpf/MainWindow.xaml.cs#L9-L43
It sounds like CompositionTarget.Rendering
is an event that fires at the rate of vsync (usually 60 Hz) and this topic is discussed on several pages:
- https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.compositiontarget.rendering?redirectedfrom=MSDN&view=windowsdesktop-6.0
- https://docs.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-render-on-a-per-frame-interval-using-compositiontarget?redirectedfrom=MSDN&view=netframeworkdesktop-4.8
- https://docs.microsoft.com/en-us/dotnet/desktop/wpf/advanced/graphics-rendering-tiers?view=netframeworkdesktop-4.8
- https://stackoverflow.com/questions/18353225/what-can-i-do-inside-compositiontarget-rendering
- https://stackoverflow.com/questions/23854176/wpf-rendering-real-time-best-practice
- https://stackoverflow.com/questions/58367035/compositiontarget-rendering-lag
- https://evanl.wordpress.com/2009/12/06/efficient-optimal-per-frame-eventing-in-wpf/
- https://stackoverflow.com/questions/16991949/how-to-make-a-render-loop-in-wpf
- https://stackoverflow.com/questions/8713864/high-performance-graphics-using-the-wpf-visual-layer/
- https://stackoverflow.com/questions/7733990/constant-framerate-in-wpf-for-game
- https://stackoverflow.com/questions/5812384/why-is-frame-rate-in-wpf-irregular-and-not-limited-to-monitor-refresh