开发者

Returning objects from another thread?

开发者 https://www.devze.com 2022-12-29 08:02 出处:网络
Trying to follow the hints laid out here, but she doesn\'t mention how to handle it when your collection needs to return a value, like so:

Trying to follow the hints laid out here, but she doesn't mention how to handle it when your collection needs to return a value, like so:

    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));
    开发者_StackOverflow社区        return val;
        }
        else
        {
            dispatcher.BeginInvoke(new DequeueDelegate(Dequeue));
        }
    }

This obviously won't work, because dispatcher.BeginInvoke doesn't return anything. What am I supposed to do?


Call Invoke in place of BeginInvoke. This will run it on the dispatcher's thread, but will execute synchronously and return the result returned by the delegate.

If you don't need the result immediately, hold onto the DispatcherOperation returned by BeginInvoke. When you do need the result, call the operation's Wait method and, if it returns DispatcherOperationStatus.Completed, read the Result property.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号