Set up a timer to handle high-cost operation in ValueChanged event.
Here is a simple case: you use a Slider
control to adjust the fontsize of a TextBlock
.
XAML:
<StackPanel>
<TextBlock x:Name="ContentText" Text="Here is the simple text"/>
<Slider x:Name="TextSizeSlider" Value="5" ValueChanged="TextSizeSlider_ValueChanged" Minimum="1"/>
</StackPanel>
Code behind:
private void TextSizeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
ContentText.FontSize = e.NewValue;
}
Of course, change the FontSize
of TextBlock
is a low-cost operation which you will not even think about optimizing. However, there are some cases that you would perform a high-cost operation like aplying blurring effect to an Image, sending a HTTP request and so on. And in those cases frequent high-cost operations can result in slowing down the performance of your app or cause some unexpected issues.
So you may want to do some tricks to handle this issue: 500ms after your change to UI and the high-cost operation should be fired.
private DispatcherTimer _timer;
private void TextSizeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
if (_timer != null) _timer.Stop();
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(0.5);
_timer.Tick += _timer_Tick;
//Remember to start the timer
_timer.Start();
}
private async void _timer_Tick(object sender, object e)
{
await BlurImage();
_timer.Stop();
_timer.Tick -= _timer_Tick;
}
private async Task BlurImage()
{
//Do your high-cost operation
}
Subscribe to JuniperPhoton's Blog
Get the latest posts delivered right to your inbox