Background timer to update UI?

喜你入骨 提交于 2020-01-11 08:29:09

问题


I got a little problem with my application.
I would like to update something on my UI every 10 seconds. I first used a DispatcherTimer for this but it will block my UI for a short time because the update method needs to load something from the web and this operation needs some time. Now I thought about some kind of background worker and I found BackgroundTasks.
The problem with Background tasks is, as far as I understood it correctly, that they are supposed to serve as updaters even if the app is suspended. I don't need that. I only would like to update if my app is running not if it is suspended.

Is there a good way to solve this? Any suggestions what to use for this?

Thanks in advance!


回答1:


You need two things for it:

  1. Timer

    You can update the UI in System.Timers.Timer with the 10 seconds interval.

  2. Dispatcher

    You need to use Dispatcher.Invoke to change the UI without holding the main UI thread. Instead the method Process should be called on a separate thread (Timer method), other than main UI thread, and use Dispatcher in it to alert main UI thread for the change.

    Process() // method to be called after regular interval in Timer
    {
        // lengthy process, i.e. data fetching and processing etc.
    
        // here comes the UI update part
        Dispatcher.Invoke((Action)delegate() { /* update UI */ });
    }
    



回答2:


You need to create a thread that runs the part of your code that gets and processes the information from the website. This way, your form will not hesitate because it will be on a different thread than the processing part.

This Article on code-project should get you started.




回答3:


Also, you could start a timer, which has a elapsed event, that occurs every time the timer passes a certain time cycle.

  1. http://www.dotnetperls.com/timer


来源:https://stackoverflow.com/questions/13537117/background-timer-to-update-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!