Returning objects from another thread?

Trying to follow the prompts outlined here , but it doesn't mention how to handle it when your collection needs to return a value, like this:

    private delegate TValue DequeueDelegate();
    public virtual TValue Dequeue()
    {
        if (dispatcher.CheckAccess())
        {
            --count;
            var pair = dict.First();
            var queue = pair.Value;
            var val = queue.Dequeue();
            if (queue.Count == 0) dict.Remove(pair.Key);
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, val));
            return val;
        }
        else
        {
            dispatcher.BeginInvoke(new DequeueDelegate(Dequeue));
        }
    }

This obviously won't work, because it dispatcher.BeginInvokereturns nothing. What should I do?

+5
source share
1 answer

Call Invokeinstead BeginInvoke. This will launch it into the dispatcher thread, but will execute synchronously and return the result returned by the delegate.

, DispatcherOperation, BeginInvoke. , Wait , DispatcherOperationStatus.Completed, Result.

+2

All Articles