Question

I have an Async DataGrid loading feature. Hence, i need to call WaitFor(). Here's that code:

WaitFor(TimeSpan.Zero, DispatcherPriority.SystemIdle);

And following are the 2 methods. Can someone explain what this methods are exactly doing?

public static void WaitFor(TimeSpan time, DispatcherPriority priority)
{
    DispatcherTimer timer = new DispatcherTimer(priority);
    timer.Tick += new EventHandler(OnDispatched);
    timer.Interval = time;
    DispatcherFrame dispatcherFrame = new DispatcherFrame(false);
    timer.Tag = dispatcherFrame;
    timer.Start();
    Dispatcher.PushFrame(dispatcherFrame);
}

public static void OnDispatched(object sender, EventArgs args)
{
    DispatcherTimer timer = (DispatcherTimer)sender;
    timer.Tick -= new EventHandler(OnDispatched);
    timer.Stop();
    DispatcherFrame frame = (DispatcherFrame)timer.Tag;
    frame.Continue = false;
}
Was it helpful?

Solution

You do not need any WaitFor(). Why waiting for something anyways? Just let the UI thread unfrozen and once data loaded the DataGrid will display them.

The methods you posted are doing the.... WaitFor mechanism. The method name explains it all :)

Here are few more details:

DispatcherTimer is a simple dumb Timer you might already know from basic C# just once tick method invoked it will be executed directly on UI thread, hence you do not need to care whether you are on UI thread or not. You always are :)

DispatcherTimer has a prority means if proprity set to high the tick invocation method will be called immediately after interval. If proprity is set to Background the tick method will be invoked when UI thread is not busy.

DispatcherFrame is the current scope you are in. Every displatcher operation has sort of scope. Each scope processes pending work items

Dispatcher.PushFrame is same as DoEvent() back when people used WinForms alot. To keep it simple with DoEvent you are forcing UI thread to do something.

To sum up you wait for things to get done in UI thread.

I hope this helps you any futher.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top