簡體   English   中英

如果從同一線程調用了Dispatcher.BeginInvoke,則該調用是否排隊?

[英]Does Dispatcher.BeginInvoke queues the call if it is called from the same thread?

如果我有類似的電話:

Application.Current.Dispatcher.BeginInvoke(() => someAction);

是從Dispatcher線程調用的,是因為它不需要排隊就可以在以后執行,還是可以立即執行,因為它不需要從一個線程更改為另一個線程?

是因為它不需要從一個線程更改為另一個線程,還是排隊等待稍后執行還是立即執行?

仍然排隊。 沒有檢查從哪個上下文調用該方法。 您可以在源代碼中看到它:

private void InvokeAsyncImpl(DispatcherOperation operation,
                             CancellationToken cancellationToken)
{
    DispatcherHooks hooks = null;
    bool succeeded = false;

    // Could be a non-dispatcher thread, lock to read
    lock(_instanceLock)
    {
        if (!cancellationToken.IsCancellationRequested &&
            !_hasShutdownFinished && 
            !Environment.HasShutdownStarted)
        {
            // Add the operation to the work queue
            operation._item = _queue.Enqueue(operation.Priority, operation);

            // Make sure we will wake up to process this operation.
            succeeded = RequestProcessing();

            if (succeeded)
            {
                // Grab the hooks to use inside the lock; but we will
                // call them below, outside of the lock.
                hooks = _hooks;
            }
            else
            {
                // Dequeue the item since we failed to request
                // processing for it.  Note we will mark it aborted
                // below.
                _queue.RemoveItem(operation._item);
            }
        } 
    }

    // Rest of method, shortened for brevity.
}

正如其他人指出的那樣,它確實要排隊。 解決此問題的一種有用方法是定義:

public void DispatchIfNecessary(Action action) {
    if (!Dispatcher.CheckAccess())
        Dispatcher.Invoke(action);
    else
        action.Invoke();
}

可以稱為:

DispatchIfNecessary(() => {
    someAction...
});

在您在Dispatcher線程中運行代碼並且所有其他排隊的BeginInvoke完成執行后,它將排隊等待執行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM