如果我有这样的电话:
Application.Current.Dispatcher.BeginInvoke(() => someAction);
从Dispatcher线程调用的是否会排队等待稍后执行或立即执行,因为它不需要从一个线程更改为另一个线程?
答案 0 :(得分:2)
是否排队等待稍后执行或立即执行 因为它不需要从一个线程更改为另一个线程?
仍然排队等候。没有检查调用该方法的上下文。你可以看到它in the source:
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.
}
答案 1 :(得分:2)
正如其他人所指出的,它确实排队等候。解决这个问题的有效方法是定义:
public void DispatchIfNecessary(Action action) {
if (!Dispatcher.CheckAccess())
Dispatcher.Invoke(action);
else
action.Invoke();
}
可以称为:
DispatchIfNecessary(() => {
someAction...
});
答案 2 :(得分:1)
在Dispatcher线程中运行的代码和所有其他排队的BeginInvoke完成执行后,它排队等待执行