0

我有一个异步 DataGrid 加载功能。因此,我需要调用 WaitFor()。这是代码:

WaitFor(TimeSpan.Zero, DispatcherPriority.SystemIdle);

以下是2种方法。有人可以解释这些方法到底在做什么吗?

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;
}
4

1 回答 1

1

您不需要任何 WaitFor()。为什么还要等待?只需让 UI 线程解冻,一旦加载数据,DataGrid 就会显示它们。

您发布的方法正在执行.... WaitFor 机制。方法名称说明了一切:)

以下是更多细节:

DispatcherTimer 是一个简单的哑定时器,你可能已经从基本的 C# 中知道了,只要调用 tick 方法,它就会直接在 UI 线程上执行,因此你不需要关心你是否在 UI 线程上。你永远是:)

DispatcherTimer 有一个优先级,如果属性设置为高,则将在间隔后立即调用滴答调用方法。如果property 设置为Background,则在UI 线程不忙时将调用tick 方法。

DispatcherFrame 是您当前所处的范围。每个调度程序操作都有一定的范围。每个范围处理待处理的工作项

当人们经常使用 WinForms 时,Dispatcher.PushFrame 与 DoEvent() 相同。为了让 DoEvent 保持简单,你强制 UI 线程做一些事情。

总而言之,您等待在 UI 线程中完成任务。

我希望这对您有所帮助。

于 2014-02-04T07:58:24.113 回答