Wednesday, January 25, 2012

OnIdle Event in WPF

The OnIdle Event is fired as soon as the computer does not have any tasks to execute. Thus it is a very convenient way to decide when refreshing graphical components. Assuming you have a program that streams a bunch of data from a given source, each time a couple of data arrive you trigger the refresh display function along with your processing functions. What will appends is that the graphical elements refreshing is pretty slow, thus the data start to accumulate in the buffer and the time lag between the data live stream and the graphical result on the screen increases.
The solution to this issue is to process the data when they arrive, but not do any refreshing on the screen nor the graphical components. The screen will be refreshed only when the computer has time, which will be the case when the event OnIdle fires.

Use the following code to subscribe to  the OnIdle Event:


using System.Windows.Interop;
       
private void Window_Loaded(object sender, RoutedEventArgs e)
{    
ComponentDispatcher.ThreadIdle += new EventHandler(OnIdle);
}

The method where to put the refreshing functions:


private void OnIdle(object sender, EventArgs e)
{
// Refreshing display functions
}

Notice that this way of processing the data and refreshing the screen, prioritize the processing (possible also the recording) of the data compared to displaying the data to the user. The human eye can only see 25 images per second anyway, so it does not make sense in most of the case to refresh each time a data arrives.

2 comments:

  1. Hi,

    I would like to master the moment to redraw my application. So I think your post answer to my problem.
    But When we have a multi-thread application, when ThreadIdle is raised?

    Have you ever try to write your own messages loop?

    You are the only person (I found) who speaks about this topic, I hope you can help me.
    Thank you in advance.

    Celine

    ReplyDelete
  2. thank you very much for your comment!

    "But When we have a multi-thread application, when ThreadIdle is raised?":
    I honestly do not know, but modern computers spend most of their time doing nothing... thus their are plenty of opportunities to execute this event :). My guess is that this function only cares about the "application thread". Its main use is to do housekeeping tasks such refreshing result on the screen.

    "Have you ever try to write your own messages loop?":
    no I had no needs for this

    Which kind of problem are you facing?

    cheers,

    Pascal

    ReplyDelete