DispatcherOperations.Wait ()
What happens if you call dispatcherOperation.Wait()
in an already executed operation? Also, the docs say it returns DispatcherOperationStatus
, but isn't it always that Completed
, since it (presumably) doesn't return until it completes?
I tried to use it like this:
private void Update()
{
while (ops.Count > 0) ops.Dequeue().Wait();
}
public void Add(T item)
{
lock (sync)
{
if (dispatcher.CheckAccess())
{
list.Add(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
else
{
ops.Enqueue(dispatcher.BeginInvoke(new Action<T>(Add), item));
}
}
}
I use this in WPF so all operations Add
should occur on the UI thread, but I figured I could just queue them up without waiting for it to switch threads and then just call Update()
before any read operations to make sure the list is updated, but my program starts to hang.
a source to share
I think I know why it hangs.
you should read the docs on DispatcherOperation.Wait there is a warning about calling wait on the same thread that was dispatched by the operation too. So what can happen is that there is an operation in the event queue, but then you call Wait from that operation from the GUI thread, since the wait for the operation to block will never be dispatched, so you just stumped guithread.
What you could do if you wanted to be absolutely sure there were no pending events, just look at the status field of the operations in the queue, you can delete all completed and if there are any you should just try again later.
Although, to be honest, you would probably be better off not worrying about this and handling Collectionchanged notifications so that you are informed exactly when new items are coming and you don't have to worry about pending actions at all.
a source to share