简体   繁体   中英

C# UWP UI dispatcher optimization (Windows IoT Core)

In my app (on a Dragonboard 410c) i have a ThreadPoolTimer. Inside the Tick-Event is a lot of work to do, most work is for processing data and update the UI. So i added a dispatcher inside the Tick-Event and process all the work there. Since the Tick-Event is called every second (Need this for updating a clock on the UI), some UI animations are sort of lagging a bit every second. As soon as i remove the the option to update the clock on the UI, all animations are running smooth.

private async void clock_Tick(ThreadPoolTimer timer)
{
    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    () =>
    {
        textBlockClock.Text = DateTime.Now.ToString("HH:mm");
        textBlockWeekDay.Text = DateTime.Now.ToString("dddd", cultureInfo);
        textBlockDate.Text = DateTime.Now.ToString("dd.MM.yyyy");

        // Do more work (call multiple methods and tasks)
    });

So the question is, is it the right approach to use just one dispatcher and add every related code in there, or should i use the dispatcher inside every called method / task for better optimization?

So the question is, is it the right approach to use just one dispatcher and add every related code in there, or should i use the dispatcher inside every called method / task for better optimization?

Ideally you want to run only UI related code on the dispatcher/UI thread. It might increase the complexity so there is a trade off. Usually, you will be fine if you separate the heavy processing code (which does not need UI thread) from the UI code and put it outside of the Dispatcher.RunAsync method, minimizing the work in UI thread to keep the UI more responsive.

private async void clock_Tick(ThreadPoolTimer timer)
{
    // Do some work.
    // ...
    // Update the UI.
    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    () => {
        textBlockClock.Text = clock;
        textBlockWeekDay.Text  weekday;
        textBlockDate.Text = date;
    });
    // Do more work.
    // ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM