Dispatcher.BeginInvoke始终返回DispatcherOperationStatus.Pending状态

Ser*_*lik 3 c# wpf multithreading mvvm

我尝试ObservableCollection使用WPF项目中的以下代码异步更新:

if (Dispatcher.Thread != Thread.CurrentThread)
{
    if (Dispatcher.Thread.ThreadState != ThreadState.Stopped && !Dispatcher.Thread.IsBackground)
    {
        Dispatcher.Invoke(new Action(() => { ChangeCollectionByAction(action); }), null);
    }
    else
    {
        var op = Dispatcher.BeginInvoke(new Action(() => { ChangeCollectionByAction(action); }), null);
        var status = op.Status;
        while (status != DispatcherOperationStatus.Completed)
        {
            status = op.Wait(TimeSpan.FromSeconds(1));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是,状态总是等于DispatcherOperationStatus.Pending.

ps:可能是我在WinForms项目中使用ElementHost的问题?

Rac*_*hel 13

如果你想在异步操作完成后运行某些东西,你应该使用它的Completed事件.

请参阅答案以获取示例

var dispatcherOp = Dispatcher.BeginInvoke( /* your method here */);
dispatcherOp.Completed += (s, e) => { /* callback code here */ };
Run Code Online (Sandbox Code Playgroud)

在您订阅之前,操作可能会完成,因此您也可以测试Status属性是否完成:

if (dispatcherOp.Status == DispatcherOperationStatus.Completed) { ... }
Run Code Online (Sandbox Code Playgroud)

至于实际问题,我不确定无法重现它.如果我不得不冒险猜测,那就是你的循环会占用当前的Dispatcher线程,所以它无法处理BeginInvoke你告诉它要处理的操作,所以它总是会坐着Pending.